/*!
 * ONNX Runtime Web v1.27.0
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License.
 */
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 __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
  if (typeof require !== "undefined") return require.apply(this, arguments);
  throw Error('Dynamic require of "' + x + '" is not supported');
});
var __esm = (fn, res) => function __init() {
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __commonJS = (cb, mod) => function __require2() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.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 = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __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 || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// 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.27.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, tensorFromMLTensor, 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 (typeof HTMLCanvasElement !== "undefined" && 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 });
    };
    tensorFromMLTensor = (mlTensor, options) => {
      const { dataType, dims, download, dispose } = options;
      return new Tensor({ location: "ml-tensor", type: dataType ?? "float32", mlTensor, 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],
      ["int4", Uint8Array],
      ["uint4", Uint8Array]
    ]);
    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 Float16Array = globalThis.Float16Array;
        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
          });
        case "ml-tensor":
          return new Tensor({
            location: "ml-tensor",
            mlTensor: tensor.mlTensor,
            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" && type !== "uint4" && type !== "int4") {
                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;
            }
            case "ml-tensor": {
              if (type !== "float32" && type !== "float16" && type !== "int32" && type !== "int64" && type !== "uint32" && type !== "uint64" && type !== "int8" && type !== "uint8" && type !== "bool" && type !== "uint4" && type !== "int4") {
                throw new TypeError(`unsupported type "${type}" to create tensor from MLTensor`);
              }
              this.mlTensorData = arg0.mlTensor;
              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 || arg0 === "uint4" || arg0 === "int4") {
                  throw new TypeError(`Creating a ${arg0} tensor from number array is not supported. Please use ${typedArrayConstructor.name} 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 if (arg1 instanceof Uint8ClampedArray) {
                if (arg0 === "uint8") {
                  data = Uint8Array.from(arg1);
                } else {
                  throw new TypeError(`A Uint8ClampedArray tensor's data must be type of uint8`);
                }
              } else if (arg0 === "float16" && arg1 instanceof Uint16Array && typedArrayConstructor !== Uint16Array) {
                data = new globalThis.Float16Array(arg1.buffer, arg1.byteOffset, arg1.length);
              } 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 if (arg0 instanceof Uint8ClampedArray) {
              type = "uint8";
              data = Uint8Array.from(arg0);
            } 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) {
          if ((type === "uint4" || type === "int4") && Math.ceil(size / 2) === this.cpuData.length) {
          } else {
            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 fromMLTensor(mlTensor, options) {
        return tensorFromMLTensor(mlTensor, 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;
      }
      get mlTensor() {
        this.ensureValid();
        if (!this.mlTensorData) {
          throw new Error("The data is not stored as a WebNN MLTensor.");
        }
        return this.mlTensorData;
      }
      // #endregion
      // #region methods
      async getData(releaseData) {
        this.ensureValid();
        switch (this.dataLocation) {
          case "cpu":
          case "cpu-pinned":
            return this.data;
          case "texture":
          case "gpu-buffer":
          case "ml-tensor": {
            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.mlTensorData = 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, TRACE_EVENT_BEGIN, TRACE_EVENT_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);
    };
    TRACE_EVENT_BEGIN = (extraMsg) => {
      if (typeof env.trace === "undefined" ? !env.wasm.trace : !env.trace) {
        return;
      }
      console.time(`ORT::${extraMsg}`);
    };
    TRACE_EVENT_END = (extraMsg) => {
      if (typeof env.trace === "undefined" ? !env.wasm.trace : !env.trace) {
        return;
      }
      console.timeEnd(`ORT::${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();
        TRACE_EVENT_BEGIN("InferenceSession.run");
        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_EVENT_END("InferenceSession.run");
        TRACE_FUNC_END();
        return returnValue;
      }
      async release() {
        return this.handler.dispose();
      }
      static async create(arg0, arg1, arg2, arg3) {
        TRACE_FUNC_BEGIN();
        TRACE_EVENT_BEGIN("InferenceSession.create");
        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_EVENT_END("InferenceSession.create");
        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;
      }
      get inputMetadata() {
        return this.handler.inputMetadata;
      }
      get outputMetadata() {
        return this.handler.outputMetadata;
      }
    };
  }
});

// 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/index.js
var esm_exports = {};
__export(esm_exports, {
  InferenceSession: () => InferenceSession2,
  TRACE: () => TRACE,
  TRACE_EVENT_BEGIN: () => TRACE_EVENT_BEGIN,
  TRACE_EVENT_END: () => TRACE_EVENT_END,
  TRACE_FUNC_BEGIN: () => TRACE_FUNC_BEGIN,
  TRACE_FUNC_END: () => TRACE_FUNC_END,
  Tensor: () => Tensor2,
  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();
  }
});

// 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"(exports) {
    "use strict";
    exports.__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;
      })()
    );
    exports.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([
            // \0asm
            0,
            97,
            115,
            109,
            // version 1
            1,
            0,
            0,
            0,
            // section "type"
            1,
            13,
            2,
            // 0, () => i32
            96,
            0,
            1,
            127,
            // 1, (i32, i32, i32, i32) => i32
            96,
            4,
            127,
            127,
            127,
            127,
            1,
            127,
            // section "function"
            3,
            7,
            6,
            // 0, type 0
            0,
            // 1, type 1
            1,
            // 2, type 1
            1,
            // 3, type 1
            1,
            // 4, type 1
            1,
            // 5, type 1
            1,
            // section "global"
            6,
            6,
            1,
            // 0, "high", mutable i32
            127,
            1,
            65,
            0,
            11,
            // section "export"
            7,
            50,
            6,
            // 0, "mul"
            3,
            109,
            117,
            108,
            0,
            1,
            // 1, "div_s"
            5,
            100,
            105,
            118,
            95,
            115,
            0,
            2,
            // 2, "div_u"
            5,
            100,
            105,
            118,
            95,
            117,
            0,
            3,
            // 3, "rem_s"
            5,
            114,
            101,
            109,
            95,
            115,
            0,
            4,
            // 4, "rem_u"
            5,
            114,
            101,
            109,
            95,
            117,
            0,
            5,
            // 5, "get_high"
            8,
            103,
            101,
            116,
            95,
            104,
            105,
            103,
            104,
            0,
            0,
            // section "code"
            10,
            191,
            1,
            6,
            // 0, "get_high"
            4,
            0,
            35,
            0,
            11,
            // 1, "mul"
            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,
            // 2, "div_s"
            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,
            // 3, "div_u"
            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,
            // 4, "rem_s"
            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,
            // 5, "rem_u"
            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 {
    }
    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.isSafeInteger = function isSafeInteger() {
      var top11Bits = this.high >> 21;
      if (!top11Bits) return true;
      if (this.unsigned) return false;
      return top11Bits === -1 && !(this.low === 0 && this.high === -2097152);
    };
    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
      );
    };
    if (typeof BigInt === "function") {
      Long.fromBigInt = function fromBigInt(value, unsigned) {
        var lowBits = Number(BigInt.asIntN(32, value));
        var highBits = Number(BigInt.asIntN(32, value >> BigInt(32)));
        return fromBits(lowBits, highBits, unsigned);
      };
      Long.fromValue = function fromValueWithBigInt(value, unsigned) {
        if (typeof value === "bigint") return Long.fromBigInt(value, unsigned);
        return fromValue(value, unsigned);
      };
      LongPrototype.toBigInt = function toBigInt() {
        var lowBigInt = BigInt(this.low >>> 0);
        var highBigInt = BigInt(this.unsigned ? this.high >>> 0 : this.high);
        return highBigInt << BigInt(32) | lowBigInt;
      };
    }
    long_default = Long;
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/arg-type.js
var require_arg_type = __commonJS({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/arg-type.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ArgType = void 0;
    var ArgType2;
    (function(ArgType3) {
      ArgType3[ArgType3["INPUT"] = 0] = "INPUT";
      ArgType3[ArgType3["OUTPUT"] = 1] = "OUTPUT";
    })(ArgType2 || (exports.ArgType = ArgType2 = {}));
  }
});

// web/node_modules/flatbuffers/js/constants.js
var require_constants = __commonJS({
  "web/node_modules/flatbuffers/js/constants.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SIZE_PREFIX_LENGTH = exports.FILE_IDENTIFIER_LENGTH = exports.SIZEOF_INT = exports.SIZEOF_SHORT = void 0;
    exports.SIZEOF_SHORT = 2;
    exports.SIZEOF_INT = 4;
    exports.FILE_IDENTIFIER_LENGTH = 4;
    exports.SIZE_PREFIX_LENGTH = 4;
  }
});

// web/node_modules/flatbuffers/js/utils.js
var require_utils = __commonJS({
  "web/node_modules/flatbuffers/js/utils.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.isLittleEndian = exports.float64 = exports.float32 = exports.int32 = void 0;
    exports.int32 = new Int32Array(2);
    exports.float32 = new Float32Array(exports.int32.buffer);
    exports.float64 = new Float64Array(exports.int32.buffer);
    exports.isLittleEndian = new Uint16Array(new Uint8Array([1, 0]).buffer)[0] === 1;
  }
});

// web/node_modules/flatbuffers/js/encoding.js
var require_encoding = __commonJS({
  "web/node_modules/flatbuffers/js/encoding.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Encoding = void 0;
    var Encoding;
    (function(Encoding2) {
      Encoding2[Encoding2["UTF8_BYTES"] = 1] = "UTF8_BYTES";
      Encoding2[Encoding2["UTF16_STRING"] = 2] = "UTF16_STRING";
    })(Encoding || (exports.Encoding = Encoding = {}));
  }
});

// web/node_modules/flatbuffers/js/byte-buffer.js
var require_byte_buffer = __commonJS({
  "web/node_modules/flatbuffers/js/byte-buffer.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ByteBuffer = void 0;
    var constants_js_1 = require_constants();
    var encoding_js_1 = require_encoding();
    var utils_js_1 = require_utils();
    var ByteBuffer2 = class _ByteBuffer {
      /**
       * Create a new ByteBuffer with a given array of bytes (`Uint8Array`)
       */
      constructor(bytes_) {
        this.bytes_ = bytes_;
        this.position_ = 0;
        this.text_decoder_ = new TextDecoder();
      }
      /**
       * Create and allocate a new ByteBuffer with a given size.
       */
      static allocate(byte_size) {
        return new _ByteBuffer(new Uint8Array(byte_size));
      }
      clear() {
        this.position_ = 0;
      }
      /**
       * Get the underlying `Uint8Array`.
       */
      bytes() {
        return this.bytes_;
      }
      /**
       * Get the buffer's position.
       */
      position() {
        return this.position_;
      }
      /**
       * Set the buffer's position.
       */
      setPosition(position) {
        this.position_ = position;
      }
      /**
       * Get the buffer's capacity.
       */
      capacity() {
        return this.bytes_.length;
      }
      readInt8(offset) {
        return this.readUint8(offset) << 24 >> 24;
      }
      readUint8(offset) {
        return this.bytes_[offset];
      }
      readInt16(offset) {
        return this.readUint16(offset) << 16 >> 16;
      }
      readUint16(offset) {
        return this.bytes_[offset] | this.bytes_[offset + 1] << 8;
      }
      readInt32(offset) {
        return this.bytes_[offset] | this.bytes_[offset + 1] << 8 | this.bytes_[offset + 2] << 16 | this.bytes_[offset + 3] << 24;
      }
      readUint32(offset) {
        return this.readInt32(offset) >>> 0;
      }
      readInt64(offset) {
        return BigInt.asIntN(64, BigInt(this.readUint32(offset)) + (BigInt(this.readUint32(offset + 4)) << BigInt(32)));
      }
      readUint64(offset) {
        return BigInt.asUintN(64, BigInt(this.readUint32(offset)) + (BigInt(this.readUint32(offset + 4)) << BigInt(32)));
      }
      readFloat32(offset) {
        utils_js_1.int32[0] = this.readInt32(offset);
        return utils_js_1.float32[0];
      }
      readFloat64(offset) {
        utils_js_1.int32[utils_js_1.isLittleEndian ? 0 : 1] = this.readInt32(offset);
        utils_js_1.int32[utils_js_1.isLittleEndian ? 1 : 0] = this.readInt32(offset + 4);
        return utils_js_1.float64[0];
      }
      writeInt8(offset, value) {
        this.bytes_[offset] = value;
      }
      writeUint8(offset, value) {
        this.bytes_[offset] = value;
      }
      writeInt16(offset, value) {
        this.bytes_[offset] = value;
        this.bytes_[offset + 1] = value >> 8;
      }
      writeUint16(offset, value) {
        this.bytes_[offset] = value;
        this.bytes_[offset + 1] = value >> 8;
      }
      writeInt32(offset, value) {
        this.bytes_[offset] = value;
        this.bytes_[offset + 1] = value >> 8;
        this.bytes_[offset + 2] = value >> 16;
        this.bytes_[offset + 3] = value >> 24;
      }
      writeUint32(offset, value) {
        this.bytes_[offset] = value;
        this.bytes_[offset + 1] = value >> 8;
        this.bytes_[offset + 2] = value >> 16;
        this.bytes_[offset + 3] = value >> 24;
      }
      writeInt64(offset, value) {
        this.writeInt32(offset, Number(BigInt.asIntN(32, value)));
        this.writeInt32(offset + 4, Number(BigInt.asIntN(32, value >> BigInt(32))));
      }
      writeUint64(offset, value) {
        this.writeUint32(offset, Number(BigInt.asUintN(32, value)));
        this.writeUint32(offset + 4, Number(BigInt.asUintN(32, value >> BigInt(32))));
      }
      writeFloat32(offset, value) {
        utils_js_1.float32[0] = value;
        this.writeInt32(offset, utils_js_1.int32[0]);
      }
      writeFloat64(offset, value) {
        utils_js_1.float64[0] = value;
        this.writeInt32(offset, utils_js_1.int32[utils_js_1.isLittleEndian ? 0 : 1]);
        this.writeInt32(offset + 4, utils_js_1.int32[utils_js_1.isLittleEndian ? 1 : 0]);
      }
      /**
       * Return the file identifier.   Behavior is undefined for FlatBuffers whose
       * schema does not include a file_identifier (likely points at padding or the
       * start of a the root vtable).
       */
      getBufferIdentifier() {
        if (this.bytes_.length < this.position_ + constants_js_1.SIZEOF_INT + constants_js_1.FILE_IDENTIFIER_LENGTH) {
          throw new Error("FlatBuffers: ByteBuffer is too short to contain an identifier.");
        }
        let result = "";
        for (let i = 0; i < constants_js_1.FILE_IDENTIFIER_LENGTH; i++) {
          result += String.fromCharCode(this.readInt8(this.position_ + constants_js_1.SIZEOF_INT + i));
        }
        return result;
      }
      /**
       * Look up a field in the vtable, return an offset into the object, or 0 if the
       * field is not present.
       */
      __offset(bb_pos, vtable_offset) {
        const vtable = bb_pos - this.readInt32(bb_pos);
        return vtable_offset < this.readInt16(vtable) ? this.readInt16(vtable + vtable_offset) : 0;
      }
      /**
       * Initialize any Table-derived type to point to the union at the given offset.
       */
      __union(t, offset) {
        t.bb_pos = offset + this.readInt32(offset);
        t.bb = this;
        return t;
      }
      /**
       * Create a JavaScript string from UTF-8 data stored inside the FlatBuffer.
       * This allocates a new string and converts to wide chars upon each access.
       *
       * To avoid the conversion to string, pass Encoding.UTF8_BYTES as the
       * "optionalEncoding" argument. This is useful for avoiding conversion when
       * the data will just be packaged back up in another FlatBuffer later on.
       *
       * @param offset
       * @param opt_encoding Defaults to UTF16_STRING
       */
      __string(offset, opt_encoding) {
        offset += this.readInt32(offset);
        const length = this.readInt32(offset);
        offset += constants_js_1.SIZEOF_INT;
        const utf8bytes = this.bytes_.subarray(offset, offset + length);
        if (opt_encoding === encoding_js_1.Encoding.UTF8_BYTES)
          return utf8bytes;
        else
          return this.text_decoder_.decode(utf8bytes);
      }
      /**
       * Handle unions that can contain string as its member, if a Table-derived type then initialize it,
       * if a string then return a new one
       *
       * WARNING: strings are immutable in JS so we can't change the string that the user gave us, this
       * makes the behaviour of __union_with_string different compared to __union
       */
      __union_with_string(o, offset) {
        if (typeof o === "string") {
          return this.__string(offset);
        }
        return this.__union(o, offset);
      }
      /**
       * Retrieve the relative offset stored at "offset"
       */
      __indirect(offset) {
        return offset + this.readInt32(offset);
      }
      /**
       * Get the start of data of a vector whose offset is stored at "offset" in this object.
       */
      __vector(offset) {
        return offset + this.readInt32(offset) + constants_js_1.SIZEOF_INT;
      }
      /**
       * Get the length of a vector whose offset is stored at "offset" in this object.
       */
      __vector_len(offset) {
        return this.readInt32(offset + this.readInt32(offset));
      }
      __has_identifier(ident) {
        if (ident.length != constants_js_1.FILE_IDENTIFIER_LENGTH) {
          throw new Error("FlatBuffers: file identifier must be length " + constants_js_1.FILE_IDENTIFIER_LENGTH);
        }
        for (let i = 0; i < constants_js_1.FILE_IDENTIFIER_LENGTH; i++) {
          if (ident.charCodeAt(i) != this.readInt8(this.position() + constants_js_1.SIZEOF_INT + i)) {
            return false;
          }
        }
        return true;
      }
      /**
       * A helper function for generating list for obj api
       */
      createScalarList(listAccessor, listLength) {
        const ret = [];
        for (let i = 0; i < listLength; ++i) {
          const val = listAccessor(i);
          if (val !== null) {
            ret.push(val);
          }
        }
        return ret;
      }
      /**
       * A helper function for generating list for obj api
       * @param listAccessor function that accepts an index and return data at that index
       * @param listLength listLength
       * @param res result list
       */
      createObjList(listAccessor, listLength) {
        const ret = [];
        for (let i = 0; i < listLength; ++i) {
          const val = listAccessor(i);
          if (val !== null) {
            ret.push(val.unpack());
          }
        }
        return ret;
      }
    };
    exports.ByteBuffer = ByteBuffer2;
  }
});

// web/node_modules/flatbuffers/js/builder.js
var require_builder = __commonJS({
  "web/node_modules/flatbuffers/js/builder.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Builder = void 0;
    var byte_buffer_js_1 = require_byte_buffer();
    var constants_js_1 = require_constants();
    var Builder = class _Builder {
      /**
       * Create a FlatBufferBuilder.
       */
      constructor(opt_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;
        this.string_maps = null;
        this.text_encoder = new TextEncoder();
        let initial_size;
        if (!opt_initial_size) {
          initial_size = 1024;
        } else {
          initial_size = opt_initial_size;
        }
        this.bb = byte_buffer_js_1.ByteBuffer.allocate(initial_size);
        this.space = initial_size;
      }
      clear() {
        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;
        this.string_maps = null;
      }
      /**
       * In order to save space, fields that are set to their default value
       * don't get serialized into the buffer. Forcing defaults provides a
       * way to manually disable this optimization.
       *
       * @param forceDefaults true always serializes default values
       */
      forceDefaults(forceDefaults) {
        this.force_defaults = forceDefaults;
      }
      /**
       * Get the ByteBuffer representing the FlatBuffer. Only call this after you've
       * called finish(). The actual data starts at the ByteBuffer's current position,
       * not necessarily at 0.
       */
      dataBuffer() {
        return this.bb;
      }
      /**
       * Get the bytes representing the FlatBuffer. Only call this after you've
       * called finish().
       */
      asUint8Array() {
        return this.bb.bytes().subarray(this.bb.position(), this.bb.position() + this.offset());
      }
      /**
       * Prepare to write an element of `size` after `additional_bytes` have been
       * written, e.g. if you write a string, you need to align such the int length
       * field is aligned to 4 bytes, and the string data follows it directly. If all
       * you need to do is alignment, `additional_bytes` will be 0.
       *
       * @param size This is the of the new element to write
       * @param additional_bytes The padding size
       */
      prep(size, additional_bytes) {
        if (size > this.minalign) {
          this.minalign = size;
        }
        const align_size = ~(this.bb.capacity() - this.space + additional_bytes) + 1 & size - 1;
        while (this.space < align_size + size + additional_bytes) {
          const old_buf_size = this.bb.capacity();
          this.bb = _Builder.growByteBuffer(this.bb);
          this.space += this.bb.capacity() - old_buf_size;
        }
        this.pad(align_size);
      }
      pad(byte_size) {
        for (let i = 0; i < byte_size; i++) {
          this.bb.writeInt8(--this.space, 0);
        }
      }
      writeInt8(value) {
        this.bb.writeInt8(this.space -= 1, value);
      }
      writeInt16(value) {
        this.bb.writeInt16(this.space -= 2, value);
      }
      writeInt32(value) {
        this.bb.writeInt32(this.space -= 4, value);
      }
      writeInt64(value) {
        this.bb.writeInt64(this.space -= 8, value);
      }
      writeFloat32(value) {
        this.bb.writeFloat32(this.space -= 4, value);
      }
      writeFloat64(value) {
        this.bb.writeFloat64(this.space -= 8, value);
      }
      /**
       * Add an `int8` to the buffer, properly aligned, and grows the buffer (if necessary).
       * @param value The `int8` to add the buffer.
       */
      addInt8(value) {
        this.prep(1, 0);
        this.writeInt8(value);
      }
      /**
       * Add an `int16` to the buffer, properly aligned, and grows the buffer (if necessary).
       * @param value The `int16` to add the buffer.
       */
      addInt16(value) {
        this.prep(2, 0);
        this.writeInt16(value);
      }
      /**
       * Add an `int32` to the buffer, properly aligned, and grows the buffer (if necessary).
       * @param value The `int32` to add the buffer.
       */
      addInt32(value) {
        this.prep(4, 0);
        this.writeInt32(value);
      }
      /**
       * Add an `int64` to the buffer, properly aligned, and grows the buffer (if necessary).
       * @param value The `int64` to add the buffer.
       */
      addInt64(value) {
        this.prep(8, 0);
        this.writeInt64(value);
      }
      /**
       * Add a `float32` to the buffer, properly aligned, and grows the buffer (if necessary).
       * @param value The `float32` to add the buffer.
       */
      addFloat32(value) {
        this.prep(4, 0);
        this.writeFloat32(value);
      }
      /**
       * Add a `float64` to the buffer, properly aligned, and grows the buffer (if necessary).
       * @param value The `float64` to add the buffer.
       */
      addFloat64(value) {
        this.prep(8, 0);
        this.writeFloat64(value);
      }
      addFieldInt8(voffset, value, defaultValue) {
        if (this.force_defaults || value != defaultValue) {
          this.addInt8(value);
          this.slot(voffset);
        }
      }
      addFieldInt16(voffset, value, defaultValue) {
        if (this.force_defaults || value != defaultValue) {
          this.addInt16(value);
          this.slot(voffset);
        }
      }
      addFieldInt32(voffset, value, defaultValue) {
        if (this.force_defaults || value != defaultValue) {
          this.addInt32(value);
          this.slot(voffset);
        }
      }
      addFieldInt64(voffset, value, defaultValue) {
        if (this.force_defaults || value !== defaultValue) {
          this.addInt64(value);
          this.slot(voffset);
        }
      }
      addFieldFloat32(voffset, value, defaultValue) {
        if (this.force_defaults || value != defaultValue) {
          this.addFloat32(value);
          this.slot(voffset);
        }
      }
      addFieldFloat64(voffset, value, defaultValue) {
        if (this.force_defaults || value != defaultValue) {
          this.addFloat64(value);
          this.slot(voffset);
        }
      }
      addFieldOffset(voffset, value, defaultValue) {
        if (this.force_defaults || value != defaultValue) {
          this.addOffset(value);
          this.slot(voffset);
        }
      }
      /**
       * Structs are stored inline, so nothing additional is being added. `d` is always 0.
       */
      addFieldStruct(voffset, value, defaultValue) {
        if (value != defaultValue) {
          this.nested(value);
          this.slot(voffset);
        }
      }
      /**
       * Structures are always stored inline, they need to be created right
       * where they're used.  You'll get this assertion failure if you
       * created it elsewhere.
       */
      nested(obj) {
        if (obj != this.offset()) {
          throw new TypeError("FlatBuffers: struct must be serialized inline.");
        }
      }
      /**
       * Should not be creating any other object, string or vector
       * while an object is being constructed
       */
      notNested() {
        if (this.isNested) {
          throw new TypeError("FlatBuffers: object serialization must not be nested.");
        }
      }
      /**
       * Set the current vtable at `voffset` to the current location in the buffer.
       */
      slot(voffset) {
        if (this.vtable !== null)
          this.vtable[voffset] = this.offset();
      }
      /**
       * @returns Offset relative to the end of the buffer.
       */
      offset() {
        return this.bb.capacity() - this.space;
      }
      /**
       * Doubles the size of the backing ByteBuffer and copies the old data towards
       * the end of the new buffer (since we build the buffer backwards).
       *
       * @param bb The current buffer with the existing data
       * @returns A new byte buffer with the old data copied
       * to it. The data is located at the end of the buffer.
       *
       * uint8Array.set() formally takes {Array<number>|ArrayBufferView}, so to pass
       * it a uint8Array we need to suppress the type check:
       * @suppress {checkTypes}
       */
      static growByteBuffer(bb) {
        const old_buf_size = bb.capacity();
        if (old_buf_size & 3221225472) {
          throw new Error("FlatBuffers: cannot grow buffer beyond 2 gigabytes.");
        }
        const new_buf_size = old_buf_size << 1;
        const nbb = byte_buffer_js_1.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;
      }
      /**
       * Adds on offset, relative to where it will be written.
       *
       * @param offset The offset to add.
       */
      addOffset(offset) {
        this.prep(constants_js_1.SIZEOF_INT, 0);
        this.writeInt32(this.offset() - offset + constants_js_1.SIZEOF_INT);
      }
      /**
       * Start encoding a new object in the buffer.  Users will not usually need to
       * call this directly. The FlatBuffers compiler will generate helper methods
       * that call this method internally.
       */
      startObject(numfields) {
        this.notNested();
        if (this.vtable == null) {
          this.vtable = [];
        }
        this.vtable_in_use = numfields;
        for (let i = 0; i < numfields; i++) {
          this.vtable[i] = 0;
        }
        this.isNested = true;
        this.object_start = this.offset();
      }
      /**
       * Finish off writing the object that is under construction.
       *
       * @returns The offset to the object inside `dataBuffer`
       */
      endObject() {
        if (this.vtable == null || !this.isNested) {
          throw new Error("FlatBuffers: endObject called without startObject");
        }
        this.addInt32(0);
        const vtableloc = this.offset();
        let i = this.vtable_in_use - 1;
        for (; i >= 0 && this.vtable[i] == 0; i--) {
        }
        const trimmed_size = i + 1;
        for (; i >= 0; i--) {
          this.addInt16(this.vtable[i] != 0 ? vtableloc - this.vtable[i] : 0);
        }
        const standard_fields = 2;
        this.addInt16(vtableloc - this.object_start);
        const len = (trimmed_size + standard_fields) * constants_js_1.SIZEOF_SHORT;
        this.addInt16(len);
        let existing_vtable = 0;
        const vt1 = this.space;
        outer_loop: for (i = 0; i < this.vtables.length; i++) {
          const vt2 = this.bb.capacity() - this.vtables[i];
          if (len == this.bb.readInt16(vt2)) {
            for (let j = constants_js_1.SIZEOF_SHORT; j < len; j += constants_js_1.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;
      }
      /**
       * Finalize a buffer, poiting to the given `root_table`.
       */
      finish(root_table, opt_file_identifier, opt_size_prefix) {
        const size_prefix = opt_size_prefix ? constants_js_1.SIZE_PREFIX_LENGTH : 0;
        if (opt_file_identifier) {
          const file_identifier = opt_file_identifier;
          this.prep(this.minalign, constants_js_1.SIZEOF_INT + constants_js_1.FILE_IDENTIFIER_LENGTH + size_prefix);
          if (file_identifier.length != constants_js_1.FILE_IDENTIFIER_LENGTH) {
            throw new TypeError("FlatBuffers: file identifier must be length " + constants_js_1.FILE_IDENTIFIER_LENGTH);
          }
          for (let i = constants_js_1.FILE_IDENTIFIER_LENGTH - 1; i >= 0; i--) {
            this.writeInt8(file_identifier.charCodeAt(i));
          }
        }
        this.prep(this.minalign, constants_js_1.SIZEOF_INT + size_prefix);
        this.addOffset(root_table);
        if (size_prefix) {
          this.addInt32(this.bb.capacity() - this.space);
        }
        this.bb.setPosition(this.space);
      }
      /**
       * Finalize a size prefixed buffer, pointing to the given `root_table`.
       */
      finishSizePrefixed(root_table, opt_file_identifier) {
        this.finish(root_table, opt_file_identifier, true);
      }
      /**
       * This checks a required field has been set in a given table that has
       * just been constructed.
       */
      requiredField(table, field) {
        const table_start = this.bb.capacity() - table;
        const vtable_start = table_start - this.bb.readInt32(table_start);
        const ok = field < this.bb.readInt16(vtable_start) && this.bb.readInt16(vtable_start + field) != 0;
        if (!ok) {
          throw new TypeError("FlatBuffers: field " + field + " must be set");
        }
      }
      /**
       * Start a new array/vector of objects.  Users usually will not call
       * this directly. The FlatBuffers compiler will create a start/end
       * method for vector types in generated code.
       *
       * @param elem_size The size of each element in the array
       * @param num_elems The number of elements in the array
       * @param alignment The alignment of the array
       */
      startVector(elem_size, num_elems, alignment) {
        this.notNested();
        this.vector_num_elems = num_elems;
        this.prep(constants_js_1.SIZEOF_INT, elem_size * num_elems);
        this.prep(alignment, elem_size * num_elems);
      }
      /**
       * Finish off the creation of an array and all its elements. The array must be
       * created with `startVector`.
       *
       * @returns The offset at which the newly created array
       * starts.
       */
      endVector() {
        this.writeInt32(this.vector_num_elems);
        return this.offset();
      }
      /**
       * Encode the string `s` in the buffer using UTF-8. If the string passed has
       * already been seen, we return the offset of the already written string
       *
       * @param s The string to encode
       * @return The offset in the buffer where the encoded string starts
       */
      createSharedString(s) {
        if (!s) {
          return 0;
        }
        if (!this.string_maps) {
          this.string_maps = /* @__PURE__ */ new Map();
        }
        if (this.string_maps.has(s)) {
          return this.string_maps.get(s);
        }
        const offset = this.createString(s);
        this.string_maps.set(s, offset);
        return offset;
      }
      /**
       * Encode the string `s` in the buffer using UTF-8. If a Uint8Array is passed
       * instead of a string, it is assumed to contain valid UTF-8 encoded data.
       *
       * @param s The string to encode
       * @return The offset in the buffer where the encoded string starts
       */
      createString(s) {
        if (s === null || s === void 0) {
          return 0;
        }
        let utf8;
        if (s instanceof Uint8Array) {
          utf8 = s;
        } else {
          utf8 = this.text_encoder.encode(s);
        }
        this.addInt8(0);
        this.startVector(1, utf8.length, 1);
        this.bb.setPosition(this.space -= utf8.length);
        this.bb.bytes().set(utf8, this.space);
        return this.endVector();
      }
      /**
       * Create a byte vector.
       *
       * @param v The bytes to add
       * @returns The offset in the buffer where the byte vector starts
       */
      createByteVector(v) {
        if (v === null || v === void 0) {
          return 0;
        }
        this.startVector(1, v.length, 1);
        this.bb.setPosition(this.space -= v.length);
        this.bb.bytes().set(v, this.space);
        return this.endVector();
      }
      /**
       * A helper function to pack an object
       *
       * @returns offset of obj
       */
      createObjectOffset(obj) {
        if (obj === null) {
          return 0;
        }
        if (typeof obj === "string") {
          return this.createString(obj);
        } else {
          return obj.pack(this);
        }
      }
      /**
       * A helper function to pack a list of object
       *
       * @returns list of offsets of each non null object
       */
      createObjectOffsetList(list) {
        const ret = [];
        for (let i = 0; i < list.length; ++i) {
          const val = list[i];
          if (val !== null) {
            ret.push(this.createObjectOffset(val));
          } else {
            throw new TypeError("FlatBuffers: Argument for createObjectOffsetList cannot contain null.");
          }
        }
        return ret;
      }
      createStructOffsetList(list, startFunc) {
        startFunc(this, list.length);
        this.createObjectOffsetList(list.slice().reverse());
        return this.endVector();
      }
    };
    exports.Builder = Builder;
  }
});

// web/node_modules/flatbuffers/js/flatbuffers.js
var require_flatbuffers = __commonJS({
  "web/node_modules/flatbuffers/js/flatbuffers.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Encoding = exports.ByteBuffer = exports.Builder = exports.isLittleEndian = exports.int32 = exports.float64 = exports.float32 = exports.SIZE_PREFIX_LENGTH = exports.SIZEOF_SHORT = exports.SIZEOF_INT = exports.FILE_IDENTIFIER_LENGTH = void 0;
    var constants_js_1 = require_constants();
    Object.defineProperty(exports, "FILE_IDENTIFIER_LENGTH", { enumerable: true, get: function() {
      return constants_js_1.FILE_IDENTIFIER_LENGTH;
    } });
    Object.defineProperty(exports, "SIZEOF_INT", { enumerable: true, get: function() {
      return constants_js_1.SIZEOF_INT;
    } });
    Object.defineProperty(exports, "SIZEOF_SHORT", { enumerable: true, get: function() {
      return constants_js_1.SIZEOF_SHORT;
    } });
    Object.defineProperty(exports, "SIZE_PREFIX_LENGTH", { enumerable: true, get: function() {
      return constants_js_1.SIZE_PREFIX_LENGTH;
    } });
    var utils_js_1 = require_utils();
    Object.defineProperty(exports, "float32", { enumerable: true, get: function() {
      return utils_js_1.float32;
    } });
    Object.defineProperty(exports, "float64", { enumerable: true, get: function() {
      return utils_js_1.float64;
    } });
    Object.defineProperty(exports, "int32", { enumerable: true, get: function() {
      return utils_js_1.int32;
    } });
    Object.defineProperty(exports, "isLittleEndian", { enumerable: true, get: function() {
      return utils_js_1.isLittleEndian;
    } });
    var builder_js_1 = require_builder();
    Object.defineProperty(exports, "Builder", { enumerable: true, get: function() {
      return builder_js_1.Builder;
    } });
    var byte_buffer_js_1 = require_byte_buffer();
    Object.defineProperty(exports, "ByteBuffer", { enumerable: true, get: function() {
      return byte_buffer_js_1.ByteBuffer;
    } });
    var encoding_js_1 = require_encoding();
    Object.defineProperty(exports, "Encoding", { enumerable: true, get: function() {
      return encoding_js_1.Encoding;
    } });
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/arg-type-and-index.js
var require_arg_type_and_index = __commonJS({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/arg-type-and-index.js"(exports) {
    "use strict";
    var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = {
          enumerable: true,
          get: function() {
            return m[k];
          }
        };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    });
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    } : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function(o2) {
          var ar = [];
          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
          return ar;
        };
        return ownKeys(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ArgTypeAndIndex = void 0;
    var flatbuffers2 = __importStar(require_flatbuffers());
    var arg_type_js_1 = require_arg_type();
    var ArgTypeAndIndex2 = class _ArgTypeAndIndex {
      constructor() {
        this.bb = null;
        this.bb_pos = 0;
      }
      __init(i, bb) {
        this.bb_pos = i;
        this.bb = bb;
        return this;
      }
      static getRootAsArgTypeAndIndex(bb, obj) {
        return (obj || new _ArgTypeAndIndex()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      static getSizePrefixedRootAsArgTypeAndIndex(bb, obj) {
        bb.setPosition(bb.position() + flatbuffers2.SIZE_PREFIX_LENGTH);
        return (obj || new _ArgTypeAndIndex()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      argType() {
        const offset = this.bb.__offset(this.bb_pos, 4);
        return offset ? this.bb.readInt8(this.bb_pos + offset) : arg_type_js_1.ArgType.INPUT;
      }
      index() {
        const offset = this.bb.__offset(this.bb_pos, 6);
        return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
      }
      static startArgTypeAndIndex(builder) {
        builder.startObject(2);
      }
      static addArgType(builder, argType) {
        builder.addFieldInt8(0, argType, arg_type_js_1.ArgType.INPUT);
      }
      static addIndex(builder, index) {
        builder.addFieldInt32(1, index, 0);
      }
      static endArgTypeAndIndex(builder) {
        const offset = builder.endObject();
        return offset;
      }
      static createArgTypeAndIndex(builder, argType, index) {
        _ArgTypeAndIndex.startArgTypeAndIndex(builder);
        _ArgTypeAndIndex.addArgType(builder, argType);
        _ArgTypeAndIndex.addIndex(builder, index);
        return _ArgTypeAndIndex.endArgTypeAndIndex(builder);
      }
    };
    exports.ArgTypeAndIndex = ArgTypeAndIndex2;
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/attribute-type.js
var require_attribute_type = __commonJS({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/attribute-type.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.AttributeType = void 0;
    var AttributeType2;
    (function(AttributeType3) {
      AttributeType3[AttributeType3["UNDEFINED"] = 0] = "UNDEFINED";
      AttributeType3[AttributeType3["FLOAT"] = 1] = "FLOAT";
      AttributeType3[AttributeType3["INT"] = 2] = "INT";
      AttributeType3[AttributeType3["STRING"] = 3] = "STRING";
      AttributeType3[AttributeType3["TENSOR"] = 4] = "TENSOR";
      AttributeType3[AttributeType3["GRAPH"] = 5] = "GRAPH";
      AttributeType3[AttributeType3["FLOATS"] = 6] = "FLOATS";
      AttributeType3[AttributeType3["INTS"] = 7] = "INTS";
      AttributeType3[AttributeType3["STRINGS"] = 8] = "STRINGS";
      AttributeType3[AttributeType3["TENSORS"] = 9] = "TENSORS";
      AttributeType3[AttributeType3["GRAPHS"] = 10] = "GRAPHS";
      AttributeType3[AttributeType3["SPARSE_TENSOR"] = 11] = "SPARSE_TENSOR";
      AttributeType3[AttributeType3["SPARSE_TENSORS"] = 12] = "SPARSE_TENSORS";
    })(AttributeType2 || (exports.AttributeType = AttributeType2 = {}));
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/node-type.js
var require_node_type = __commonJS({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/node-type.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.NodeType = void 0;
    var NodeType2;
    (function(NodeType3) {
      NodeType3[NodeType3["Primitive"] = 0] = "Primitive";
      NodeType3[NodeType3["Fused"] = 1] = "Fused";
    })(NodeType2 || (exports.NodeType = NodeType2 = {}));
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/node.js
var require_node = __commonJS({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/node.js"(exports) {
    "use strict";
    var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = {
          enumerable: true,
          get: function() {
            return m[k];
          }
        };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    });
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    } : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function(o2) {
          var ar = [];
          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
          return ar;
        };
        return ownKeys(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Node = void 0;
    var flatbuffers2 = __importStar(require_flatbuffers());
    var attribute_js_1 = require_attribute();
    var node_type_js_1 = require_node_type();
    var Node3 = class _Node {
      constructor() {
        this.bb = null;
        this.bb_pos = 0;
      }
      __init(i, bb) {
        this.bb_pos = i;
        this.bb = bb;
        return this;
      }
      static getRootAsNode(bb, obj) {
        return (obj || new _Node()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      static getSizePrefixedRootAsNode(bb, obj) {
        bb.setPosition(bb.position() + flatbuffers2.SIZE_PREFIX_LENGTH);
        return (obj || new _Node()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      name(optionalEncoding) {
        const offset = this.bb.__offset(this.bb_pos, 4);
        return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
      }
      docString(optionalEncoding) {
        const offset = this.bb.__offset(this.bb_pos, 6);
        return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
      }
      domain(optionalEncoding) {
        const offset = this.bb.__offset(this.bb_pos, 8);
        return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
      }
      sinceVersion() {
        const offset = this.bb.__offset(this.bb_pos, 10);
        return offset ? this.bb.readInt32(this.bb_pos + offset) : 0;
      }
      index() {
        const offset = this.bb.__offset(this.bb_pos, 12);
        return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
      }
      opType(optionalEncoding) {
        const offset = this.bb.__offset(this.bb_pos, 14);
        return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
      }
      type() {
        const offset = this.bb.__offset(this.bb_pos, 16);
        return offset ? this.bb.readInt32(this.bb_pos + offset) : node_type_js_1.NodeType.Primitive;
      }
      executionProviderType(optionalEncoding) {
        const offset = this.bb.__offset(this.bb_pos, 18);
        return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
      }
      inputs(index, optionalEncoding) {
        const offset = this.bb.__offset(this.bb_pos, 20);
        return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
      }
      inputsLength() {
        const offset = this.bb.__offset(this.bb_pos, 20);
        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
      }
      outputs(index, optionalEncoding) {
        const offset = this.bb.__offset(this.bb_pos, 22);
        return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
      }
      outputsLength() {
        const offset = this.bb.__offset(this.bb_pos, 22);
        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
      }
      attributes(index, obj) {
        const offset = this.bb.__offset(this.bb_pos, 24);
        return offset ? (obj || new attribute_js_1.Attribute()).__init(
          this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4),
          this.bb
        ) : null;
      }
      attributesLength() {
        const offset = this.bb.__offset(this.bb_pos, 24);
        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
      }
      inputArgCounts(index) {
        const offset = this.bb.__offset(this.bb_pos, 26);
        return offset ? this.bb.readInt32(this.bb.__vector(this.bb_pos + offset) + index * 4) : 0;
      }
      inputArgCountsLength() {
        const offset = this.bb.__offset(this.bb_pos, 26);
        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
      }
      inputArgCountsArray() {
        const 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) {
        const offset = this.bb.__offset(this.bb_pos, 28);
        return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
      }
      implicitInputsLength() {
        const offset = this.bb.__offset(this.bb_pos, 28);
        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
      }
      static startNode(builder) {
        builder.startObject(13);
      }
      static addName(builder, nameOffset) {
        builder.addFieldOffset(0, nameOffset, 0);
      }
      static addDocString(builder, docStringOffset) {
        builder.addFieldOffset(1, docStringOffset, 0);
      }
      static addDomain(builder, domainOffset) {
        builder.addFieldOffset(2, domainOffset, 0);
      }
      static addSinceVersion(builder, sinceVersion) {
        builder.addFieldInt32(3, sinceVersion, 0);
      }
      static addIndex(builder, index) {
        builder.addFieldInt32(4, index, 0);
      }
      static addOpType(builder, opTypeOffset) {
        builder.addFieldOffset(5, opTypeOffset, 0);
      }
      static addType(builder, type) {
        builder.addFieldInt32(6, type, node_type_js_1.NodeType.Primitive);
      }
      static addExecutionProviderType(builder, executionProviderTypeOffset) {
        builder.addFieldOffset(7, executionProviderTypeOffset, 0);
      }
      static addInputs(builder, inputsOffset) {
        builder.addFieldOffset(8, inputsOffset, 0);
      }
      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();
      }
      static startInputsVector(builder, numElems) {
        builder.startVector(4, numElems, 4);
      }
      static addOutputs(builder, outputsOffset) {
        builder.addFieldOffset(9, outputsOffset, 0);
      }
      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();
      }
      static startOutputsVector(builder, numElems) {
        builder.startVector(4, numElems, 4);
      }
      static addAttributes(builder, attributesOffset) {
        builder.addFieldOffset(10, attributesOffset, 0);
      }
      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();
      }
      static startAttributesVector(builder, numElems) {
        builder.startVector(4, numElems, 4);
      }
      static addInputArgCounts(builder, inputArgCountsOffset) {
        builder.addFieldOffset(11, inputArgCountsOffset, 0);
      }
      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();
      }
      static startInputArgCountsVector(builder, numElems) {
        builder.startVector(4, numElems, 4);
      }
      static addImplicitInputs(builder, implicitInputsOffset) {
        builder.addFieldOffset(12, implicitInputsOffset, 0);
      }
      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();
      }
      static startImplicitInputsVector(builder, numElems) {
        builder.startVector(4, numElems, 4);
      }
      static endNode(builder) {
        const offset = builder.endObject();
        return offset;
      }
      static createNode(builder, nameOffset, docStringOffset, domainOffset, sinceVersion, index, opTypeOffset, type, executionProviderTypeOffset, inputsOffset, outputsOffset, attributesOffset, inputArgCountsOffset, implicitInputsOffset) {
        _Node.startNode(builder);
        _Node.addName(builder, nameOffset);
        _Node.addDocString(builder, docStringOffset);
        _Node.addDomain(builder, domainOffset);
        _Node.addSinceVersion(builder, sinceVersion);
        _Node.addIndex(builder, index);
        _Node.addOpType(builder, opTypeOffset);
        _Node.addType(builder, type);
        _Node.addExecutionProviderType(builder, executionProviderTypeOffset);
        _Node.addInputs(builder, inputsOffset);
        _Node.addOutputs(builder, outputsOffset);
        _Node.addAttributes(builder, attributesOffset);
        _Node.addInputArgCounts(builder, inputArgCountsOffset);
        _Node.addImplicitInputs(builder, implicitInputsOffset);
        return _Node.endNode(builder);
      }
    };
    exports.Node = Node3;
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/edge-end.js
var require_edge_end = __commonJS({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/edge-end.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.EdgeEnd = void 0;
    var EdgeEnd2 = class {
      constructor() {
        this.bb = null;
        this.bb_pos = 0;
      }
      __init(i, bb) {
        this.bb_pos = i;
        this.bb = bb;
        return this;
      }
      nodeIndex() {
        return this.bb.readUint32(this.bb_pos);
      }
      srcArgIndex() {
        return this.bb.readInt32(this.bb_pos + 4);
      }
      dstArgIndex() {
        return this.bb.readInt32(this.bb_pos + 8);
      }
      static sizeOf() {
        return 12;
      }
      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();
      }
    };
    exports.EdgeEnd = EdgeEnd2;
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/node-edge.js
var require_node_edge = __commonJS({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/node-edge.js"(exports) {
    "use strict";
    var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = {
          enumerable: true,
          get: function() {
            return m[k];
          }
        };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    });
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    } : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function(o2) {
          var ar = [];
          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
          return ar;
        };
        return ownKeys(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.NodeEdge = void 0;
    var flatbuffers2 = __importStar(require_flatbuffers());
    var edge_end_js_1 = require_edge_end();
    var NodeEdge2 = class _NodeEdge {
      constructor() {
        this.bb = null;
        this.bb_pos = 0;
      }
      __init(i, bb) {
        this.bb_pos = i;
        this.bb = bb;
        return this;
      }
      static getRootAsNodeEdge(bb, obj) {
        return (obj || new _NodeEdge()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      static getSizePrefixedRootAsNodeEdge(bb, obj) {
        bb.setPosition(bb.position() + flatbuffers2.SIZE_PREFIX_LENGTH);
        return (obj || new _NodeEdge()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      nodeIndex() {
        const offset = this.bb.__offset(this.bb_pos, 4);
        return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
      }
      inputEdges(index, obj) {
        const offset = this.bb.__offset(this.bb_pos, 6);
        return offset ? (obj || new edge_end_js_1.EdgeEnd()).__init(this.bb.__vector(this.bb_pos + offset) + index * 12, this.bb) : null;
      }
      inputEdgesLength() {
        const offset = this.bb.__offset(this.bb_pos, 6);
        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
      }
      outputEdges(index, obj) {
        const offset = this.bb.__offset(this.bb_pos, 8);
        return offset ? (obj || new edge_end_js_1.EdgeEnd()).__init(this.bb.__vector(this.bb_pos + offset) + index * 12, this.bb) : null;
      }
      outputEdgesLength() {
        const offset = this.bb.__offset(this.bb_pos, 8);
        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
      }
      static startNodeEdge(builder) {
        builder.startObject(3);
      }
      static addNodeIndex(builder, nodeIndex) {
        builder.addFieldInt32(0, nodeIndex, 0);
      }
      static addInputEdges(builder, inputEdgesOffset) {
        builder.addFieldOffset(1, inputEdgesOffset, 0);
      }
      static startInputEdgesVector(builder, numElems) {
        builder.startVector(12, numElems, 4);
      }
      static addOutputEdges(builder, outputEdgesOffset) {
        builder.addFieldOffset(2, outputEdgesOffset, 0);
      }
      static startOutputEdgesVector(builder, numElems) {
        builder.startVector(12, numElems, 4);
      }
      static endNodeEdge(builder) {
        const 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);
      }
    };
    exports.NodeEdge = NodeEdge2;
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/nodes-to-optimize-indices.js
var require_nodes_to_optimize_indices = __commonJS({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/nodes-to-optimize-indices.js"(exports) {
    "use strict";
    var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = {
          enumerable: true,
          get: function() {
            return m[k];
          }
        };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    });
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    } : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function(o2) {
          var ar = [];
          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
          return ar;
        };
        return ownKeys(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.NodesToOptimizeIndices = void 0;
    var flatbuffers2 = __importStar(require_flatbuffers());
    var NodesToOptimizeIndices2 = class _NodesToOptimizeIndices {
      constructor() {
        this.bb = null;
        this.bb_pos = 0;
      }
      __init(i, bb) {
        this.bb_pos = i;
        this.bb = bb;
        return this;
      }
      static getRootAsNodesToOptimizeIndices(bb, obj) {
        return (obj || new _NodesToOptimizeIndices()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      static getSizePrefixedRootAsNodesToOptimizeIndices(bb, obj) {
        bb.setPosition(bb.position() + flatbuffers2.SIZE_PREFIX_LENGTH);
        return (obj || new _NodesToOptimizeIndices()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      nodeIndices(index) {
        const offset = this.bb.__offset(this.bb_pos, 4);
        return offset ? this.bb.readUint32(this.bb.__vector(this.bb_pos + offset) + index * 4) : 0;
      }
      nodeIndicesLength() {
        const offset = this.bb.__offset(this.bb_pos, 4);
        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
      }
      nodeIndicesArray() {
        const 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;
      }
      numInputs() {
        const offset = this.bb.__offset(this.bb_pos, 6);
        return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
      }
      numOutputs() {
        const offset = this.bb.__offset(this.bb_pos, 8);
        return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
      }
      hasVariadicInput() {
        const offset = this.bb.__offset(this.bb_pos, 10);
        return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
      }
      hasVariadicOutput() {
        const offset = this.bb.__offset(this.bb_pos, 12);
        return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false;
      }
      numVariadicInputs() {
        const offset = this.bb.__offset(this.bb_pos, 14);
        return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
      }
      numVariadicOutputs() {
        const offset = this.bb.__offset(this.bb_pos, 16);
        return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
      }
      static startNodesToOptimizeIndices(builder) {
        builder.startObject(7);
      }
      static addNodeIndices(builder, nodeIndicesOffset) {
        builder.addFieldOffset(0, nodeIndicesOffset, 0);
      }
      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();
      }
      static startNodeIndicesVector(builder, numElems) {
        builder.startVector(4, numElems, 4);
      }
      static addNumInputs(builder, numInputs) {
        builder.addFieldInt32(1, numInputs, 0);
      }
      static addNumOutputs(builder, numOutputs) {
        builder.addFieldInt32(2, numOutputs, 0);
      }
      static addHasVariadicInput(builder, hasVariadicInput) {
        builder.addFieldInt8(3, +hasVariadicInput, 0);
      }
      static addHasVariadicOutput(builder, hasVariadicOutput) {
        builder.addFieldInt8(4, +hasVariadicOutput, 0);
      }
      static addNumVariadicInputs(builder, numVariadicInputs) {
        builder.addFieldInt32(5, numVariadicInputs, 0);
      }
      static addNumVariadicOutputs(builder, numVariadicOutputs) {
        builder.addFieldInt32(6, numVariadicOutputs, 0);
      }
      static endNodesToOptimizeIndices(builder) {
        const offset = builder.endObject();
        return offset;
      }
      static createNodesToOptimizeIndices(builder, nodeIndicesOffset, numInputs, numOutputs, hasVariadicInput, hasVariadicOutput, numVariadicInputs, numVariadicOutputs) {
        _NodesToOptimizeIndices.startNodesToOptimizeIndices(builder);
        _NodesToOptimizeIndices.addNodeIndices(builder, nodeIndicesOffset);
        _NodesToOptimizeIndices.addNumInputs(builder, numInputs);
        _NodesToOptimizeIndices.addNumOutputs(builder, numOutputs);
        _NodesToOptimizeIndices.addHasVariadicInput(builder, hasVariadicInput);
        _NodesToOptimizeIndices.addHasVariadicOutput(builder, hasVariadicOutput);
        _NodesToOptimizeIndices.addNumVariadicInputs(builder, numVariadicInputs);
        _NodesToOptimizeIndices.addNumVariadicOutputs(builder, numVariadicOutputs);
        return _NodesToOptimizeIndices.endNodesToOptimizeIndices(builder);
      }
    };
    exports.NodesToOptimizeIndices = NodesToOptimizeIndices2;
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/runtime-optimization-record.js
var require_runtime_optimization_record = __commonJS({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/runtime-optimization-record.js"(exports) {
    "use strict";
    var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = {
          enumerable: true,
          get: function() {
            return m[k];
          }
        };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    });
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    } : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function(o2) {
          var ar = [];
          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
          return ar;
        };
        return ownKeys(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RuntimeOptimizationRecord = void 0;
    var flatbuffers2 = __importStar(require_flatbuffers());
    var nodes_to_optimize_indices_js_1 = require_nodes_to_optimize_indices();
    var RuntimeOptimizationRecord2 = class _RuntimeOptimizationRecord {
      constructor() {
        this.bb = null;
        this.bb_pos = 0;
      }
      __init(i, bb) {
        this.bb_pos = i;
        this.bb = bb;
        return this;
      }
      static getRootAsRuntimeOptimizationRecord(bb, obj) {
        return (obj || new _RuntimeOptimizationRecord()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      static getSizePrefixedRootAsRuntimeOptimizationRecord(bb, obj) {
        bb.setPosition(bb.position() + flatbuffers2.SIZE_PREFIX_LENGTH);
        return (obj || new _RuntimeOptimizationRecord()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      actionId(optionalEncoding) {
        const offset = this.bb.__offset(this.bb_pos, 4);
        return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
      }
      nodesToOptimizeIndices(obj) {
        const offset = this.bb.__offset(this.bb_pos, 6);
        return offset ? (obj || new nodes_to_optimize_indices_js_1.NodesToOptimizeIndices()).__init(
          this.bb.__indirect(this.bb_pos + offset),
          this.bb
        ) : null;
      }
      producedOpIds(index, optionalEncoding) {
        const offset = this.bb.__offset(this.bb_pos, 10);
        return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
      }
      producedOpIdsLength() {
        const offset = this.bb.__offset(this.bb_pos, 10);
        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
      }
      static startRuntimeOptimizationRecord(builder) {
        builder.startObject(4);
      }
      static addActionId(builder, actionIdOffset) {
        builder.addFieldOffset(0, actionIdOffset, 0);
      }
      static addNodesToOptimizeIndices(builder, nodesToOptimizeIndicesOffset) {
        builder.addFieldOffset(1, nodesToOptimizeIndicesOffset, 0);
      }
      static addProducedOpIds(builder, producedOpIdsOffset) {
        builder.addFieldOffset(3, producedOpIdsOffset, 0);
      }
      static createProducedOpIdsVector(builder, data) {
        builder.startVector(4, data.length, 4);
        for (let i = data.length - 1; i >= 0; i--) {
          builder.addOffset(data[i]);
        }
        return builder.endVector();
      }
      static startProducedOpIdsVector(builder, numElems) {
        builder.startVector(4, numElems, 4);
      }
      static endRuntimeOptimizationRecord(builder) {
        const offset = builder.endObject();
        return offset;
      }
    };
    exports.RuntimeOptimizationRecord = RuntimeOptimizationRecord2;
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/runtime-optimization-record-container-entry.js
var require_runtime_optimization_record_container_entry = __commonJS({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/runtime-optimization-record-container-entry.js"(exports) {
    "use strict";
    var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = {
          enumerable: true,
          get: function() {
            return m[k];
          }
        };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    });
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    } : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function(o2) {
          var ar = [];
          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
          return ar;
        };
        return ownKeys(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RuntimeOptimizationRecordContainerEntry = void 0;
    var flatbuffers2 = __importStar(require_flatbuffers());
    var runtime_optimization_record_js_1 = require_runtime_optimization_record();
    var RuntimeOptimizationRecordContainerEntry2 = class _RuntimeOptimizationRecordContainerEntry {
      constructor() {
        this.bb = null;
        this.bb_pos = 0;
      }
      __init(i, bb) {
        this.bb_pos = i;
        this.bb = bb;
        return this;
      }
      static getRootAsRuntimeOptimizationRecordContainerEntry(bb, obj) {
        return (obj || new _RuntimeOptimizationRecordContainerEntry()).__init(
          bb.readInt32(bb.position()) + bb.position(),
          bb
        );
      }
      static getSizePrefixedRootAsRuntimeOptimizationRecordContainerEntry(bb, obj) {
        bb.setPosition(bb.position() + flatbuffers2.SIZE_PREFIX_LENGTH);
        return (obj || new _RuntimeOptimizationRecordContainerEntry()).__init(
          bb.readInt32(bb.position()) + bb.position(),
          bb
        );
      }
      optimizerName(optionalEncoding) {
        const offset = this.bb.__offset(this.bb_pos, 4);
        return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
      }
      runtimeOptimizationRecords(index, obj) {
        const offset = this.bb.__offset(this.bb_pos, 6);
        return offset ? (obj || new runtime_optimization_record_js_1.RuntimeOptimizationRecord()).__init(
          this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4),
          this.bb
        ) : null;
      }
      runtimeOptimizationRecordsLength() {
        const offset = this.bb.__offset(this.bb_pos, 6);
        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
      }
      static startRuntimeOptimizationRecordContainerEntry(builder) {
        builder.startObject(2);
      }
      static addOptimizerName(builder, optimizerNameOffset) {
        builder.addFieldOffset(0, optimizerNameOffset, 0);
      }
      static addRuntimeOptimizationRecords(builder, runtimeOptimizationRecordsOffset) {
        builder.addFieldOffset(1, runtimeOptimizationRecordsOffset, 0);
      }
      static createRuntimeOptimizationRecordsVector(builder, data) {
        builder.startVector(4, data.length, 4);
        for (let i = data.length - 1; i >= 0; i--) {
          builder.addOffset(data[i]);
        }
        return builder.endVector();
      }
      static startRuntimeOptimizationRecordsVector(builder, numElems) {
        builder.startVector(4, numElems, 4);
      }
      static endRuntimeOptimizationRecordContainerEntry(builder) {
        const offset = builder.endObject();
        builder.requiredField(offset, 4);
        return offset;
      }
      static createRuntimeOptimizationRecordContainerEntry(builder, optimizerNameOffset, runtimeOptimizationRecordsOffset) {
        _RuntimeOptimizationRecordContainerEntry.startRuntimeOptimizationRecordContainerEntry(builder);
        _RuntimeOptimizationRecordContainerEntry.addOptimizerName(builder, optimizerNameOffset);
        _RuntimeOptimizationRecordContainerEntry.addRuntimeOptimizationRecords(builder, runtimeOptimizationRecordsOffset);
        return _RuntimeOptimizationRecordContainerEntry.endRuntimeOptimizationRecordContainerEntry(builder);
      }
    };
    exports.RuntimeOptimizationRecordContainerEntry = RuntimeOptimizationRecordContainerEntry2;
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/runtime-optimizations.js
var require_runtime_optimizations = __commonJS({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/runtime-optimizations.js"(exports) {
    "use strict";
    var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = {
          enumerable: true,
          get: function() {
            return m[k];
          }
        };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    });
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    } : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function(o2) {
          var ar = [];
          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
          return ar;
        };
        return ownKeys(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.RuntimeOptimizations = void 0;
    var flatbuffers2 = __importStar(require_flatbuffers());
    var runtime_optimization_record_container_entry_js_1 = require_runtime_optimization_record_container_entry();
    var RuntimeOptimizations2 = class _RuntimeOptimizations {
      constructor() {
        this.bb = null;
        this.bb_pos = 0;
      }
      __init(i, bb) {
        this.bb_pos = i;
        this.bb = bb;
        return this;
      }
      static getRootAsRuntimeOptimizations(bb, obj) {
        return (obj || new _RuntimeOptimizations()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      static getSizePrefixedRootAsRuntimeOptimizations(bb, obj) {
        bb.setPosition(bb.position() + flatbuffers2.SIZE_PREFIX_LENGTH);
        return (obj || new _RuntimeOptimizations()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      /**
       * mapping from optimizer name to [RuntimeOptimizationRecord]
       */
      records(index, obj) {
        const offset = this.bb.__offset(this.bb_pos, 4);
        return offset ? (obj || new runtime_optimization_record_container_entry_js_1.RuntimeOptimizationRecordContainerEntry()).__init(
          this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4),
          this.bb
        ) : null;
      }
      recordsLength() {
        const offset = this.bb.__offset(this.bb_pos, 4);
        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
      }
      static startRuntimeOptimizations(builder) {
        builder.startObject(1);
      }
      static addRecords(builder, recordsOffset) {
        builder.addFieldOffset(0, recordsOffset, 0);
      }
      static createRecordsVector(builder, data) {
        builder.startVector(4, data.length, 4);
        for (let i = data.length - 1; i >= 0; i--) {
          builder.addOffset(data[i]);
        }
        return builder.endVector();
      }
      static startRecordsVector(builder, numElems) {
        builder.startVector(4, numElems, 4);
      }
      static endRuntimeOptimizations(builder) {
        const offset = builder.endObject();
        return offset;
      }
      static createRuntimeOptimizations(builder, recordsOffset) {
        _RuntimeOptimizations.startRuntimeOptimizations(builder);
        _RuntimeOptimizations.addRecords(builder, recordsOffset);
        return _RuntimeOptimizations.endRuntimeOptimizations(builder);
      }
    };
    exports.RuntimeOptimizations = RuntimeOptimizations2;
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/tensor-data-type.js
var require_tensor_data_type = __commonJS({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/tensor-data-type.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TensorDataType = void 0;
    var TensorDataType2;
    (function(TensorDataType3) {
      TensorDataType3[TensorDataType3["UNDEFINED"] = 0] = "UNDEFINED";
      TensorDataType3[TensorDataType3["FLOAT"] = 1] = "FLOAT";
      TensorDataType3[TensorDataType3["UINT8"] = 2] = "UINT8";
      TensorDataType3[TensorDataType3["INT8"] = 3] = "INT8";
      TensorDataType3[TensorDataType3["UINT16"] = 4] = "UINT16";
      TensorDataType3[TensorDataType3["INT16"] = 5] = "INT16";
      TensorDataType3[TensorDataType3["INT32"] = 6] = "INT32";
      TensorDataType3[TensorDataType3["INT64"] = 7] = "INT64";
      TensorDataType3[TensorDataType3["STRING"] = 8] = "STRING";
      TensorDataType3[TensorDataType3["BOOL"] = 9] = "BOOL";
      TensorDataType3[TensorDataType3["FLOAT16"] = 10] = "FLOAT16";
      TensorDataType3[TensorDataType3["DOUBLE"] = 11] = "DOUBLE";
      TensorDataType3[TensorDataType3["UINT32"] = 12] = "UINT32";
      TensorDataType3[TensorDataType3["UINT64"] = 13] = "UINT64";
      TensorDataType3[TensorDataType3["COMPLEX64"] = 14] = "COMPLEX64";
      TensorDataType3[TensorDataType3["COMPLEX128"] = 15] = "COMPLEX128";
      TensorDataType3[TensorDataType3["BFLOAT16"] = 16] = "BFLOAT16";
      TensorDataType3[TensorDataType3["FLOAT8E4M3FN"] = 17] = "FLOAT8E4M3FN";
      TensorDataType3[TensorDataType3["FLOAT8E4M3FNUZ"] = 18] = "FLOAT8E4M3FNUZ";
      TensorDataType3[TensorDataType3["FLOAT8E5M2"] = 19] = "FLOAT8E5M2";
      TensorDataType3[TensorDataType3["FLOAT8E5M2FNUZ"] = 20] = "FLOAT8E5M2FNUZ";
    })(TensorDataType2 || (exports.TensorDataType = TensorDataType2 = {}));
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/tensor.js
var require_tensor = __commonJS({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/tensor.js"(exports) {
    "use strict";
    var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = {
          enumerable: true,
          get: function() {
            return m[k];
          }
        };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    });
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    } : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function(o2) {
          var ar = [];
          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
          return ar;
        };
        return ownKeys(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Tensor = void 0;
    var flatbuffers2 = __importStar(require_flatbuffers());
    var tensor_data_type_js_1 = require_tensor_data_type();
    var Tensor5 = class _Tensor {
      constructor() {
        this.bb = null;
        this.bb_pos = 0;
      }
      __init(i, bb) {
        this.bb_pos = i;
        this.bb = bb;
        return this;
      }
      static getRootAsTensor(bb, obj) {
        return (obj || new _Tensor()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      static getSizePrefixedRootAsTensor(bb, obj) {
        bb.setPosition(bb.position() + flatbuffers2.SIZE_PREFIX_LENGTH);
        return (obj || new _Tensor()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      name(optionalEncoding) {
        const offset = this.bb.__offset(this.bb_pos, 4);
        return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
      }
      docString(optionalEncoding) {
        const offset = this.bb.__offset(this.bb_pos, 6);
        return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
      }
      dims(index) {
        const offset = this.bb.__offset(this.bb_pos, 8);
        return offset ? this.bb.readInt64(this.bb.__vector(this.bb_pos + offset) + index * 8) : BigInt(0);
      }
      dimsLength() {
        const offset = this.bb.__offset(this.bb_pos, 8);
        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
      }
      dataType() {
        const offset = this.bb.__offset(this.bb_pos, 10);
        return offset ? this.bb.readInt32(this.bb_pos + offset) : tensor_data_type_js_1.TensorDataType.UNDEFINED;
      }
      rawData(index) {
        const offset = this.bb.__offset(this.bb_pos, 12);
        return offset ? this.bb.readUint8(this.bb.__vector(this.bb_pos + offset) + index) : 0;
      }
      rawDataLength() {
        const offset = this.bb.__offset(this.bb_pos, 12);
        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
      }
      rawDataArray() {
        const 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) {
        const offset = this.bb.__offset(this.bb_pos, 14);
        return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
      }
      stringDataLength() {
        const offset = this.bb.__offset(this.bb_pos, 14);
        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
      }
      externalDataOffset() {
        const offset = this.bb.__offset(this.bb_pos, 16);
        return offset ? this.bb.readInt64(this.bb_pos + offset) : BigInt("-1");
      }
      static startTensor(builder) {
        builder.startObject(7);
      }
      static addName(builder, nameOffset) {
        builder.addFieldOffset(0, nameOffset, 0);
      }
      static addDocString(builder, docStringOffset) {
        builder.addFieldOffset(1, docStringOffset, 0);
      }
      static addDims(builder, dimsOffset) {
        builder.addFieldOffset(2, dimsOffset, 0);
      }
      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();
      }
      static startDimsVector(builder, numElems) {
        builder.startVector(8, numElems, 8);
      }
      static addDataType(builder, dataType) {
        builder.addFieldInt32(3, dataType, tensor_data_type_js_1.TensorDataType.UNDEFINED);
      }
      static addRawData(builder, rawDataOffset) {
        builder.addFieldOffset(4, rawDataOffset, 0);
      }
      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();
      }
      static startRawDataVector(builder, numElems) {
        builder.startVector(1, numElems, 1);
      }
      static addStringData(builder, stringDataOffset) {
        builder.addFieldOffset(5, stringDataOffset, 0);
      }
      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();
      }
      static startStringDataVector(builder, numElems) {
        builder.startVector(4, numElems, 4);
      }
      static addExternalDataOffset(builder, externalDataOffset) {
        builder.addFieldInt64(6, externalDataOffset, BigInt("-1"));
      }
      static endTensor(builder) {
        const offset = builder.endObject();
        return offset;
      }
      static createTensor(builder, nameOffset, docStringOffset, dimsOffset, dataType, rawDataOffset, stringDataOffset, externalDataOffset) {
        _Tensor.startTensor(builder);
        _Tensor.addName(builder, nameOffset);
        _Tensor.addDocString(builder, docStringOffset);
        _Tensor.addDims(builder, dimsOffset);
        _Tensor.addDataType(builder, dataType);
        _Tensor.addRawData(builder, rawDataOffset);
        _Tensor.addStringData(builder, stringDataOffset);
        _Tensor.addExternalDataOffset(builder, externalDataOffset);
        return _Tensor.endTensor(builder);
      }
    };
    exports.Tensor = Tensor5;
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/sparse-tensor.js
var require_sparse_tensor = __commonJS({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/sparse-tensor.js"(exports) {
    "use strict";
    var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = {
          enumerable: true,
          get: function() {
            return m[k];
          }
        };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    });
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    } : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function(o2) {
          var ar = [];
          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
          return ar;
        };
        return ownKeys(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SparseTensor = void 0;
    var flatbuffers2 = __importStar(require_flatbuffers());
    var tensor_js_1 = require_tensor();
    var SparseTensor2 = class _SparseTensor {
      constructor() {
        this.bb = null;
        this.bb_pos = 0;
      }
      __init(i, bb) {
        this.bb_pos = i;
        this.bb = bb;
        return this;
      }
      static getRootAsSparseTensor(bb, obj) {
        return (obj || new _SparseTensor()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      static getSizePrefixedRootAsSparseTensor(bb, obj) {
        bb.setPosition(bb.position() + flatbuffers2.SIZE_PREFIX_LENGTH);
        return (obj || new _SparseTensor()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      values(obj) {
        const offset = this.bb.__offset(this.bb_pos, 4);
        return offset ? (obj || new tensor_js_1.Tensor()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null;
      }
      indices(obj) {
        const offset = this.bb.__offset(this.bb_pos, 6);
        return offset ? (obj || new tensor_js_1.Tensor()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null;
      }
      dims(index) {
        const offset = this.bb.__offset(this.bb_pos, 8);
        return offset ? this.bb.readInt64(this.bb.__vector(this.bb_pos + offset) + index * 8) : BigInt(0);
      }
      dimsLength() {
        const offset = this.bb.__offset(this.bb_pos, 8);
        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
      }
      static startSparseTensor(builder) {
        builder.startObject(3);
      }
      static addValues(builder, valuesOffset) {
        builder.addFieldOffset(0, valuesOffset, 0);
      }
      static addIndices(builder, indicesOffset) {
        builder.addFieldOffset(1, indicesOffset, 0);
      }
      static addDims(builder, dimsOffset) {
        builder.addFieldOffset(2, dimsOffset, 0);
      }
      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();
      }
      static startDimsVector(builder, numElems) {
        builder.startVector(8, numElems, 8);
      }
      static endSparseTensor(builder) {
        const offset = builder.endObject();
        return offset;
      }
    };
    exports.SparseTensor = SparseTensor2;
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/map-type.js
var require_map_type = __commonJS({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/map-type.js"(exports) {
    "use strict";
    var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = {
          enumerable: true,
          get: function() {
            return m[k];
          }
        };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    });
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    } : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function(o2) {
          var ar = [];
          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
          return ar;
        };
        return ownKeys(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MapType = void 0;
    var flatbuffers2 = __importStar(require_flatbuffers());
    var tensor_data_type_js_1 = require_tensor_data_type();
    var type_info_js_1 = require_type_info();
    var MapType2 = class _MapType {
      constructor() {
        this.bb = null;
        this.bb_pos = 0;
      }
      __init(i, bb) {
        this.bb_pos = i;
        this.bb = bb;
        return this;
      }
      static getRootAsMapType(bb, obj) {
        return (obj || new _MapType()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      static getSizePrefixedRootAsMapType(bb, obj) {
        bb.setPosition(bb.position() + flatbuffers2.SIZE_PREFIX_LENGTH);
        return (obj || new _MapType()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      keyType() {
        const offset = this.bb.__offset(this.bb_pos, 4);
        return offset ? this.bb.readInt32(this.bb_pos + offset) : tensor_data_type_js_1.TensorDataType.UNDEFINED;
      }
      valueType(obj) {
        const offset = this.bb.__offset(this.bb_pos, 6);
        return offset ? (obj || new type_info_js_1.TypeInfo()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null;
      }
      static startMapType(builder) {
        builder.startObject(2);
      }
      static addKeyType(builder, keyType) {
        builder.addFieldInt32(0, keyType, tensor_data_type_js_1.TensorDataType.UNDEFINED);
      }
      static addValueType(builder, valueTypeOffset) {
        builder.addFieldOffset(1, valueTypeOffset, 0);
      }
      static endMapType(builder) {
        const offset = builder.endObject();
        return offset;
      }
    };
    exports.MapType = MapType2;
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/sequence-type.js
var require_sequence_type = __commonJS({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/sequence-type.js"(exports) {
    "use strict";
    var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = {
          enumerable: true,
          get: function() {
            return m[k];
          }
        };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    });
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    } : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function(o2) {
          var ar = [];
          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
          return ar;
        };
        return ownKeys(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.SequenceType = void 0;
    var flatbuffers2 = __importStar(require_flatbuffers());
    var type_info_js_1 = require_type_info();
    var SequenceType2 = class _SequenceType {
      constructor() {
        this.bb = null;
        this.bb_pos = 0;
      }
      __init(i, bb) {
        this.bb_pos = i;
        this.bb = bb;
        return this;
      }
      static getRootAsSequenceType(bb, obj) {
        return (obj || new _SequenceType()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      static getSizePrefixedRootAsSequenceType(bb, obj) {
        bb.setPosition(bb.position() + flatbuffers2.SIZE_PREFIX_LENGTH);
        return (obj || new _SequenceType()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      elemType(obj) {
        const offset = this.bb.__offset(this.bb_pos, 4);
        return offset ? (obj || new type_info_js_1.TypeInfo()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null;
      }
      static startSequenceType(builder) {
        builder.startObject(1);
      }
      static addElemType(builder, elemTypeOffset) {
        builder.addFieldOffset(0, elemTypeOffset, 0);
      }
      static endSequenceType(builder) {
        const offset = builder.endObject();
        return offset;
      }
      static createSequenceType(builder, elemTypeOffset) {
        _SequenceType.startSequenceType(builder);
        _SequenceType.addElemType(builder, elemTypeOffset);
        return _SequenceType.endSequenceType(builder);
      }
    };
    exports.SequenceType = SequenceType2;
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/dimension-value-type.js
var require_dimension_value_type = __commonJS({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/dimension-value-type.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DimensionValueType = void 0;
    var DimensionValueType2;
    (function(DimensionValueType3) {
      DimensionValueType3[DimensionValueType3["UNKNOWN"] = 0] = "UNKNOWN";
      DimensionValueType3[DimensionValueType3["VALUE"] = 1] = "VALUE";
      DimensionValueType3[DimensionValueType3["PARAM"] = 2] = "PARAM";
    })(DimensionValueType2 || (exports.DimensionValueType = DimensionValueType2 = {}));
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/dimension-value.js
var require_dimension_value = __commonJS({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/dimension-value.js"(exports) {
    "use strict";
    var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = {
          enumerable: true,
          get: function() {
            return m[k];
          }
        };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    });
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    } : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function(o2) {
          var ar = [];
          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
          return ar;
        };
        return ownKeys(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DimensionValue = void 0;
    var flatbuffers2 = __importStar(require_flatbuffers());
    var dimension_value_type_js_1 = require_dimension_value_type();
    var DimensionValue2 = class _DimensionValue {
      constructor() {
        this.bb = null;
        this.bb_pos = 0;
      }
      __init(i, bb) {
        this.bb_pos = i;
        this.bb = bb;
        return this;
      }
      static getRootAsDimensionValue(bb, obj) {
        return (obj || new _DimensionValue()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      static getSizePrefixedRootAsDimensionValue(bb, obj) {
        bb.setPosition(bb.position() + flatbuffers2.SIZE_PREFIX_LENGTH);
        return (obj || new _DimensionValue()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      dimType() {
        const offset = this.bb.__offset(this.bb_pos, 4);
        return offset ? this.bb.readInt8(this.bb_pos + offset) : dimension_value_type_js_1.DimensionValueType.UNKNOWN;
      }
      dimValue() {
        const offset = this.bb.__offset(this.bb_pos, 6);
        return offset ? this.bb.readInt64(this.bb_pos + offset) : BigInt("0");
      }
      dimParam(optionalEncoding) {
        const offset = this.bb.__offset(this.bb_pos, 8);
        return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
      }
      static startDimensionValue(builder) {
        builder.startObject(3);
      }
      static addDimType(builder, dimType) {
        builder.addFieldInt8(0, dimType, dimension_value_type_js_1.DimensionValueType.UNKNOWN);
      }
      static addDimValue(builder, dimValue) {
        builder.addFieldInt64(1, dimValue, BigInt("0"));
      }
      static addDimParam(builder, dimParamOffset) {
        builder.addFieldOffset(2, dimParamOffset, 0);
      }
      static endDimensionValue(builder) {
        const 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);
      }
    };
    exports.DimensionValue = DimensionValue2;
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/dimension.js
var require_dimension = __commonJS({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/dimension.js"(exports) {
    "use strict";
    var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = {
          enumerable: true,
          get: function() {
            return m[k];
          }
        };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    });
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    } : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function(o2) {
          var ar = [];
          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
          return ar;
        };
        return ownKeys(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Dimension = void 0;
    var flatbuffers2 = __importStar(require_flatbuffers());
    var dimension_value_js_1 = require_dimension_value();
    var Dimension2 = class _Dimension {
      constructor() {
        this.bb = null;
        this.bb_pos = 0;
      }
      __init(i, bb) {
        this.bb_pos = i;
        this.bb = bb;
        return this;
      }
      static getRootAsDimension(bb, obj) {
        return (obj || new _Dimension()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      static getSizePrefixedRootAsDimension(bb, obj) {
        bb.setPosition(bb.position() + flatbuffers2.SIZE_PREFIX_LENGTH);
        return (obj || new _Dimension()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      value(obj) {
        const offset = this.bb.__offset(this.bb_pos, 4);
        return offset ? (obj || new dimension_value_js_1.DimensionValue()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null;
      }
      denotation(optionalEncoding) {
        const offset = this.bb.__offset(this.bb_pos, 6);
        return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
      }
      static startDimension(builder) {
        builder.startObject(2);
      }
      static addValue(builder, valueOffset) {
        builder.addFieldOffset(0, valueOffset, 0);
      }
      static addDenotation(builder, denotationOffset) {
        builder.addFieldOffset(1, denotationOffset, 0);
      }
      static endDimension(builder) {
        const 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);
      }
    };
    exports.Dimension = Dimension2;
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/shape.js
var require_shape = __commonJS({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/shape.js"(exports) {
    "use strict";
    var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = {
          enumerable: true,
          get: function() {
            return m[k];
          }
        };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    });
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    } : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function(o2) {
          var ar = [];
          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
          return ar;
        };
        return ownKeys(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Shape = void 0;
    var flatbuffers2 = __importStar(require_flatbuffers());
    var dimension_js_1 = require_dimension();
    var Shape2 = class _Shape {
      constructor() {
        this.bb = null;
        this.bb_pos = 0;
      }
      __init(i, bb) {
        this.bb_pos = i;
        this.bb = bb;
        return this;
      }
      static getRootAsShape(bb, obj) {
        return (obj || new _Shape()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      static getSizePrefixedRootAsShape(bb, obj) {
        bb.setPosition(bb.position() + flatbuffers2.SIZE_PREFIX_LENGTH);
        return (obj || new _Shape()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      dim(index, obj) {
        const offset = this.bb.__offset(this.bb_pos, 4);
        return offset ? (obj || new dimension_js_1.Dimension()).__init(
          this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4),
          this.bb
        ) : null;
      }
      dimLength() {
        const offset = this.bb.__offset(this.bb_pos, 4);
        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
      }
      static startShape(builder) {
        builder.startObject(1);
      }
      static addDim(builder, dimOffset) {
        builder.addFieldOffset(0, dimOffset, 0);
      }
      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();
      }
      static startDimVector(builder, numElems) {
        builder.startVector(4, numElems, 4);
      }
      static endShape(builder) {
        const offset = builder.endObject();
        return offset;
      }
      static createShape(builder, dimOffset) {
        _Shape.startShape(builder);
        _Shape.addDim(builder, dimOffset);
        return _Shape.endShape(builder);
      }
    };
    exports.Shape = Shape2;
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/tensor-type-and-shape.js
var require_tensor_type_and_shape = __commonJS({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/tensor-type-and-shape.js"(exports) {
    "use strict";
    var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = {
          enumerable: true,
          get: function() {
            return m[k];
          }
        };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    });
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    } : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function(o2) {
          var ar = [];
          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
          return ar;
        };
        return ownKeys(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TensorTypeAndShape = void 0;
    var flatbuffers2 = __importStar(require_flatbuffers());
    var shape_js_1 = require_shape();
    var tensor_data_type_js_1 = require_tensor_data_type();
    var TensorTypeAndShape2 = class _TensorTypeAndShape {
      constructor() {
        this.bb = null;
        this.bb_pos = 0;
      }
      __init(i, bb) {
        this.bb_pos = i;
        this.bb = bb;
        return this;
      }
      static getRootAsTensorTypeAndShape(bb, obj) {
        return (obj || new _TensorTypeAndShape()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      static getSizePrefixedRootAsTensorTypeAndShape(bb, obj) {
        bb.setPosition(bb.position() + flatbuffers2.SIZE_PREFIX_LENGTH);
        return (obj || new _TensorTypeAndShape()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      elemType() {
        const offset = this.bb.__offset(this.bb_pos, 4);
        return offset ? this.bb.readInt32(this.bb_pos + offset) : tensor_data_type_js_1.TensorDataType.UNDEFINED;
      }
      shape(obj) {
        const offset = this.bb.__offset(this.bb_pos, 6);
        return offset ? (obj || new shape_js_1.Shape()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null;
      }
      static startTensorTypeAndShape(builder) {
        builder.startObject(2);
      }
      static addElemType(builder, elemType) {
        builder.addFieldInt32(0, elemType, tensor_data_type_js_1.TensorDataType.UNDEFINED);
      }
      static addShape(builder, shapeOffset) {
        builder.addFieldOffset(1, shapeOffset, 0);
      }
      static endTensorTypeAndShape(builder) {
        const offset = builder.endObject();
        return offset;
      }
    };
    exports.TensorTypeAndShape = TensorTypeAndShape2;
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/type-info-value.js
var require_type_info_value = __commonJS({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/type-info-value.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TypeInfoValue = void 0;
    exports.unionToTypeInfoValue = unionToTypeInfoValue;
    exports.unionListToTypeInfoValue = unionListToTypeInfoValue;
    var map_type_js_1 = require_map_type();
    var sequence_type_js_1 = require_sequence_type();
    var tensor_type_and_shape_js_1 = require_tensor_type_and_shape();
    var TypeInfoValue2;
    (function(TypeInfoValue3) {
      TypeInfoValue3[TypeInfoValue3["NONE"] = 0] = "NONE";
      TypeInfoValue3[TypeInfoValue3["tensor_type"] = 1] = "tensor_type";
      TypeInfoValue3[TypeInfoValue3["sequence_type"] = 2] = "sequence_type";
      TypeInfoValue3[TypeInfoValue3["map_type"] = 3] = "map_type";
    })(TypeInfoValue2 || (exports.TypeInfoValue = TypeInfoValue2 = {}));
    function unionToTypeInfoValue(type, accessor) {
      switch (TypeInfoValue2[type]) {
        case "NONE":
          return null;
        case "tensor_type":
          return accessor(new tensor_type_and_shape_js_1.TensorTypeAndShape());
        case "sequence_type":
          return accessor(new sequence_type_js_1.SequenceType());
        case "map_type":
          return accessor(new map_type_js_1.MapType());
        default:
          return null;
      }
    }
    function unionListToTypeInfoValue(type, accessor, index) {
      switch (TypeInfoValue2[type]) {
        case "NONE":
          return null;
        case "tensor_type":
          return accessor(index, new tensor_type_and_shape_js_1.TensorTypeAndShape());
        case "sequence_type":
          return accessor(index, new sequence_type_js_1.SequenceType());
        case "map_type":
          return accessor(index, new map_type_js_1.MapType());
        default:
          return null;
      }
    }
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/type-info.js
var require_type_info = __commonJS({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/type-info.js"(exports) {
    "use strict";
    var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = {
          enumerable: true,
          get: function() {
            return m[k];
          }
        };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    });
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    } : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function(o2) {
          var ar = [];
          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
          return ar;
        };
        return ownKeys(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.TypeInfo = void 0;
    var flatbuffers2 = __importStar(require_flatbuffers());
    var type_info_value_js_1 = require_type_info_value();
    var TypeInfo2 = class _TypeInfo {
      constructor() {
        this.bb = null;
        this.bb_pos = 0;
      }
      __init(i, bb) {
        this.bb_pos = i;
        this.bb = bb;
        return this;
      }
      static getRootAsTypeInfo(bb, obj) {
        return (obj || new _TypeInfo()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      static getSizePrefixedRootAsTypeInfo(bb, obj) {
        bb.setPosition(bb.position() + flatbuffers2.SIZE_PREFIX_LENGTH);
        return (obj || new _TypeInfo()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      denotation(optionalEncoding) {
        const offset = this.bb.__offset(this.bb_pos, 4);
        return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
      }
      valueType() {
        const offset = this.bb.__offset(this.bb_pos, 6);
        return offset ? this.bb.readUint8(this.bb_pos + offset) : type_info_value_js_1.TypeInfoValue.NONE;
      }
      value(obj) {
        const offset = this.bb.__offset(this.bb_pos, 8);
        return offset ? this.bb.__union(obj, this.bb_pos + offset) : null;
      }
      static startTypeInfo(builder) {
        builder.startObject(3);
      }
      static addDenotation(builder, denotationOffset) {
        builder.addFieldOffset(0, denotationOffset, 0);
      }
      static addValueType(builder, valueType) {
        builder.addFieldInt8(1, valueType, type_info_value_js_1.TypeInfoValue.NONE);
      }
      static addValue(builder, valueOffset) {
        builder.addFieldOffset(2, valueOffset, 0);
      }
      static endTypeInfo(builder) {
        const 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);
      }
    };
    exports.TypeInfo = TypeInfo2;
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/value-info.js
var require_value_info = __commonJS({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/value-info.js"(exports) {
    "use strict";
    var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = {
          enumerable: true,
          get: function() {
            return m[k];
          }
        };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    });
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    } : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function(o2) {
          var ar = [];
          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
          return ar;
        };
        return ownKeys(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ValueInfo = void 0;
    var flatbuffers2 = __importStar(require_flatbuffers());
    var type_info_js_1 = require_type_info();
    var ValueInfo2 = class _ValueInfo {
      constructor() {
        this.bb = null;
        this.bb_pos = 0;
      }
      __init(i, bb) {
        this.bb_pos = i;
        this.bb = bb;
        return this;
      }
      static getRootAsValueInfo(bb, obj) {
        return (obj || new _ValueInfo()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      static getSizePrefixedRootAsValueInfo(bb, obj) {
        bb.setPosition(bb.position() + flatbuffers2.SIZE_PREFIX_LENGTH);
        return (obj || new _ValueInfo()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      name(optionalEncoding) {
        const offset = this.bb.__offset(this.bb_pos, 4);
        return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
      }
      docString(optionalEncoding) {
        const offset = this.bb.__offset(this.bb_pos, 6);
        return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
      }
      type(obj) {
        const offset = this.bb.__offset(this.bb_pos, 8);
        return offset ? (obj || new type_info_js_1.TypeInfo()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null;
      }
      static startValueInfo(builder) {
        builder.startObject(3);
      }
      static addName(builder, nameOffset) {
        builder.addFieldOffset(0, nameOffset, 0);
      }
      static addDocString(builder, docStringOffset) {
        builder.addFieldOffset(1, docStringOffset, 0);
      }
      static addType(builder, typeOffset) {
        builder.addFieldOffset(2, typeOffset, 0);
      }
      static endValueInfo(builder) {
        const offset = builder.endObject();
        return offset;
      }
    };
    exports.ValueInfo = ValueInfo2;
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/graph.js
var require_graph = __commonJS({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/graph.js"(exports) {
    "use strict";
    var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = {
          enumerable: true,
          get: function() {
            return m[k];
          }
        };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    });
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    } : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function(o2) {
          var ar = [];
          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
          return ar;
        };
        return ownKeys(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Graph = void 0;
    var flatbuffers2 = __importStar(require_flatbuffers());
    var node_js_1 = require_node();
    var node_edge_js_1 = require_node_edge();
    var runtime_optimizations_js_1 = require_runtime_optimizations();
    var sparse_tensor_js_1 = require_sparse_tensor();
    var tensor_js_1 = require_tensor();
    var value_info_js_1 = require_value_info();
    var Graph3 = class _Graph {
      constructor() {
        this.bb = null;
        this.bb_pos = 0;
      }
      __init(i, bb) {
        this.bb_pos = i;
        this.bb = bb;
        return this;
      }
      static getRootAsGraph(bb, obj) {
        return (obj || new _Graph()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      static getSizePrefixedRootAsGraph(bb, obj) {
        bb.setPosition(bb.position() + flatbuffers2.SIZE_PREFIX_LENGTH);
        return (obj || new _Graph()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      initializers(index, obj) {
        const offset = this.bb.__offset(this.bb_pos, 4);
        return offset ? (obj || new tensor_js_1.Tensor()).__init(
          this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4),
          this.bb
        ) : null;
      }
      initializersLength() {
        const offset = this.bb.__offset(this.bb_pos, 4);
        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
      }
      nodeArgs(index, obj) {
        const offset = this.bb.__offset(this.bb_pos, 6);
        return offset ? (obj || new value_info_js_1.ValueInfo()).__init(
          this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4),
          this.bb
        ) : null;
      }
      nodeArgsLength() {
        const offset = this.bb.__offset(this.bb_pos, 6);
        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
      }
      nodes(index, obj) {
        const offset = this.bb.__offset(this.bb_pos, 8);
        return offset ? (obj || new node_js_1.Node()).__init(
          this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4),
          this.bb
        ) : null;
      }
      nodesLength() {
        const offset = this.bb.__offset(this.bb_pos, 8);
        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
      }
      maxNodeIndex() {
        const offset = this.bb.__offset(this.bb_pos, 10);
        return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
      }
      nodeEdges(index, obj) {
        const offset = this.bb.__offset(this.bb_pos, 12);
        return offset ? (obj || new node_edge_js_1.NodeEdge()).__init(
          this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4),
          this.bb
        ) : null;
      }
      nodeEdgesLength() {
        const offset = this.bb.__offset(this.bb_pos, 12);
        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
      }
      inputs(index, optionalEncoding) {
        const offset = this.bb.__offset(this.bb_pos, 14);
        return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
      }
      inputsLength() {
        const offset = this.bb.__offset(this.bb_pos, 14);
        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
      }
      outputs(index, optionalEncoding) {
        const offset = this.bb.__offset(this.bb_pos, 16);
        return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
      }
      outputsLength() {
        const offset = this.bb.__offset(this.bb_pos, 16);
        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
      }
      sparseInitializers(index, obj) {
        const offset = this.bb.__offset(this.bb_pos, 18);
        return offset ? (obj || new sparse_tensor_js_1.SparseTensor()).__init(
          this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4),
          this.bb
        ) : null;
      }
      sparseInitializersLength() {
        const offset = this.bb.__offset(this.bb_pos, 18);
        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
      }
      runtimeOptimizations(obj) {
        const offset = this.bb.__offset(this.bb_pos, 20);
        return offset ? (obj || new runtime_optimizations_js_1.RuntimeOptimizations()).__init(
          this.bb.__indirect(this.bb_pos + offset),
          this.bb
        ) : null;
      }
      static startGraph(builder) {
        builder.startObject(9);
      }
      static addInitializers(builder, initializersOffset) {
        builder.addFieldOffset(0, initializersOffset, 0);
      }
      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();
      }
      static startInitializersVector(builder, numElems) {
        builder.startVector(4, numElems, 4);
      }
      static addNodeArgs(builder, nodeArgsOffset) {
        builder.addFieldOffset(1, nodeArgsOffset, 0);
      }
      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();
      }
      static startNodeArgsVector(builder, numElems) {
        builder.startVector(4, numElems, 4);
      }
      static addNodes(builder, nodesOffset) {
        builder.addFieldOffset(2, nodesOffset, 0);
      }
      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();
      }
      static startNodesVector(builder, numElems) {
        builder.startVector(4, numElems, 4);
      }
      static addMaxNodeIndex(builder, maxNodeIndex) {
        builder.addFieldInt32(3, maxNodeIndex, 0);
      }
      static addNodeEdges(builder, nodeEdgesOffset) {
        builder.addFieldOffset(4, nodeEdgesOffset, 0);
      }
      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();
      }
      static startNodeEdgesVector(builder, numElems) {
        builder.startVector(4, numElems, 4);
      }
      static addInputs(builder, inputsOffset) {
        builder.addFieldOffset(5, inputsOffset, 0);
      }
      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();
      }
      static startInputsVector(builder, numElems) {
        builder.startVector(4, numElems, 4);
      }
      static addOutputs(builder, outputsOffset) {
        builder.addFieldOffset(6, outputsOffset, 0);
      }
      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();
      }
      static startOutputsVector(builder, numElems) {
        builder.startVector(4, numElems, 4);
      }
      static addSparseInitializers(builder, sparseInitializersOffset) {
        builder.addFieldOffset(7, sparseInitializersOffset, 0);
      }
      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();
      }
      static startSparseInitializersVector(builder, numElems) {
        builder.startVector(4, numElems, 4);
      }
      static addRuntimeOptimizations(builder, runtimeOptimizationsOffset) {
        builder.addFieldOffset(8, runtimeOptimizationsOffset, 0);
      }
      static endGraph(builder) {
        const offset = builder.endObject();
        return offset;
      }
    };
    exports.Graph = Graph3;
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/attribute.js
var require_attribute = __commonJS({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/attribute.js"(exports) {
    "use strict";
    var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = {
          enumerable: true,
          get: function() {
            return m[k];
          }
        };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    });
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    } : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function(o2) {
          var ar = [];
          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
          return ar;
        };
        return ownKeys(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Attribute = void 0;
    var flatbuffers2 = __importStar(require_flatbuffers());
    var attribute_type_js_1 = require_attribute_type();
    var graph_js_1 = require_graph();
    var tensor_js_1 = require_tensor();
    var Attribute3 = class _Attribute {
      constructor() {
        this.bb = null;
        this.bb_pos = 0;
      }
      __init(i, bb) {
        this.bb_pos = i;
        this.bb = bb;
        return this;
      }
      static getRootAsAttribute(bb, obj) {
        return (obj || new _Attribute()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      static getSizePrefixedRootAsAttribute(bb, obj) {
        bb.setPosition(bb.position() + flatbuffers2.SIZE_PREFIX_LENGTH);
        return (obj || new _Attribute()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      name(optionalEncoding) {
        const offset = this.bb.__offset(this.bb_pos, 4);
        return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
      }
      docString(optionalEncoding) {
        const offset = this.bb.__offset(this.bb_pos, 6);
        return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
      }
      type() {
        const offset = this.bb.__offset(this.bb_pos, 8);
        return offset ? this.bb.readInt32(this.bb_pos + offset) : attribute_type_js_1.AttributeType.UNDEFINED;
      }
      f() {
        const offset = this.bb.__offset(this.bb_pos, 10);
        return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0;
      }
      i() {
        const offset = this.bb.__offset(this.bb_pos, 12);
        return offset ? this.bb.readInt64(this.bb_pos + offset) : BigInt("0");
      }
      s(optionalEncoding) {
        const offset = this.bb.__offset(this.bb_pos, 14);
        return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
      }
      t(obj) {
        const offset = this.bb.__offset(this.bb_pos, 16);
        return offset ? (obj || new tensor_js_1.Tensor()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null;
      }
      g(obj) {
        const offset = this.bb.__offset(this.bb_pos, 18);
        return offset ? (obj || new graph_js_1.Graph()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null;
      }
      floats(index) {
        const offset = this.bb.__offset(this.bb_pos, 20);
        return offset ? this.bb.readFloat32(this.bb.__vector(this.bb_pos + offset) + index * 4) : 0;
      }
      floatsLength() {
        const offset = this.bb.__offset(this.bb_pos, 20);
        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
      }
      floatsArray() {
        const 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;
      }
      ints(index) {
        const offset = this.bb.__offset(this.bb_pos, 22);
        return offset ? this.bb.readInt64(this.bb.__vector(this.bb_pos + offset) + index * 8) : BigInt(0);
      }
      intsLength() {
        const offset = this.bb.__offset(this.bb_pos, 22);
        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
      }
      strings(index, optionalEncoding) {
        const offset = this.bb.__offset(this.bb_pos, 24);
        return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null;
      }
      stringsLength() {
        const offset = this.bb.__offset(this.bb_pos, 24);
        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
      }
      tensors(index, obj) {
        const offset = this.bb.__offset(this.bb_pos, 26);
        return offset ? (obj || new tensor_js_1.Tensor()).__init(
          this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4),
          this.bb
        ) : null;
      }
      tensorsLength() {
        const offset = this.bb.__offset(this.bb_pos, 26);
        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
      }
      graphs(index, obj) {
        const offset = this.bb.__offset(this.bb_pos, 28);
        return offset ? (obj || new graph_js_1.Graph()).__init(
          this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4),
          this.bb
        ) : null;
      }
      graphsLength() {
        const offset = this.bb.__offset(this.bb_pos, 28);
        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
      }
      static startAttribute(builder) {
        builder.startObject(13);
      }
      static addName(builder, nameOffset) {
        builder.addFieldOffset(0, nameOffset, 0);
      }
      static addDocString(builder, docStringOffset) {
        builder.addFieldOffset(1, docStringOffset, 0);
      }
      static addType(builder, type) {
        builder.addFieldInt32(2, type, attribute_type_js_1.AttributeType.UNDEFINED);
      }
      static addF(builder, f) {
        builder.addFieldFloat32(3, f, 0);
      }
      static addI(builder, i) {
        builder.addFieldInt64(4, i, BigInt("0"));
      }
      static addS(builder, sOffset) {
        builder.addFieldOffset(5, sOffset, 0);
      }
      static addT(builder, tOffset) {
        builder.addFieldOffset(6, tOffset, 0);
      }
      static addG(builder, gOffset) {
        builder.addFieldOffset(7, gOffset, 0);
      }
      static addFloats(builder, floatsOffset) {
        builder.addFieldOffset(8, floatsOffset, 0);
      }
      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();
      }
      static startFloatsVector(builder, numElems) {
        builder.startVector(4, numElems, 4);
      }
      static addInts(builder, intsOffset) {
        builder.addFieldOffset(9, intsOffset, 0);
      }
      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();
      }
      static startIntsVector(builder, numElems) {
        builder.startVector(8, numElems, 8);
      }
      static addStrings(builder, stringsOffset) {
        builder.addFieldOffset(10, stringsOffset, 0);
      }
      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();
      }
      static startStringsVector(builder, numElems) {
        builder.startVector(4, numElems, 4);
      }
      static addTensors(builder, tensorsOffset) {
        builder.addFieldOffset(11, tensorsOffset, 0);
      }
      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();
      }
      static startTensorsVector(builder, numElems) {
        builder.startVector(4, numElems, 4);
      }
      static addGraphs(builder, graphsOffset) {
        builder.addFieldOffset(12, graphsOffset, 0);
      }
      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();
      }
      static startGraphsVector(builder, numElems) {
        builder.startVector(4, numElems, 4);
      }
      static endAttribute(builder) {
        const offset = builder.endObject();
        return offset;
      }
    };
    exports.Attribute = Attribute3;
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/deprecated-kernel-create-infos.js
var require_deprecated_kernel_create_infos = __commonJS({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/deprecated-kernel-create-infos.js"(exports) {
    "use strict";
    var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = {
          enumerable: true,
          get: function() {
            return m[k];
          }
        };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    });
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    } : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function(o2) {
          var ar = [];
          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
          return ar;
        };
        return ownKeys(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DeprecatedKernelCreateInfos = void 0;
    var flatbuffers2 = __importStar(require_flatbuffers());
    var DeprecatedKernelCreateInfos2 = class _DeprecatedKernelCreateInfos {
      constructor() {
        this.bb = null;
        this.bb_pos = 0;
      }
      __init(i, bb) {
        this.bb_pos = i;
        this.bb = bb;
        return this;
      }
      static getRootAsDeprecatedKernelCreateInfos(bb, obj) {
        return (obj || new _DeprecatedKernelCreateInfos()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      static getSizePrefixedRootAsDeprecatedKernelCreateInfos(bb, obj) {
        bb.setPosition(bb.position() + flatbuffers2.SIZE_PREFIX_LENGTH);
        return (obj || new _DeprecatedKernelCreateInfos()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      nodeIndices(index) {
        const offset = this.bb.__offset(this.bb_pos, 4);
        return offset ? this.bb.readUint32(this.bb.__vector(this.bb_pos + offset) + index * 4) : 0;
      }
      nodeIndicesLength() {
        const offset = this.bb.__offset(this.bb_pos, 4);
        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
      }
      nodeIndicesArray() {
        const 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;
      }
      kernelDefHashes(index) {
        const offset = this.bb.__offset(this.bb_pos, 6);
        return offset ? this.bb.readUint64(this.bb.__vector(this.bb_pos + offset) + index * 8) : BigInt(0);
      }
      kernelDefHashesLength() {
        const offset = this.bb.__offset(this.bb_pos, 6);
        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
      }
      static startDeprecatedKernelCreateInfos(builder) {
        builder.startObject(2);
      }
      static addNodeIndices(builder, nodeIndicesOffset) {
        builder.addFieldOffset(0, nodeIndicesOffset, 0);
      }
      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();
      }
      static startNodeIndicesVector(builder, numElems) {
        builder.startVector(4, numElems, 4);
      }
      static addKernelDefHashes(builder, kernelDefHashesOffset) {
        builder.addFieldOffset(1, kernelDefHashesOffset, 0);
      }
      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();
      }
      static startKernelDefHashesVector(builder, numElems) {
        builder.startVector(8, numElems, 8);
      }
      static endDeprecatedKernelCreateInfos(builder) {
        const offset = builder.endObject();
        return offset;
      }
      static createDeprecatedKernelCreateInfos(builder, nodeIndicesOffset, kernelDefHashesOffset) {
        _DeprecatedKernelCreateInfos.startDeprecatedKernelCreateInfos(builder);
        _DeprecatedKernelCreateInfos.addNodeIndices(builder, nodeIndicesOffset);
        _DeprecatedKernelCreateInfos.addKernelDefHashes(builder, kernelDefHashesOffset);
        return _DeprecatedKernelCreateInfos.endDeprecatedKernelCreateInfos(builder);
      }
    };
    exports.DeprecatedKernelCreateInfos = DeprecatedKernelCreateInfos2;
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/deprecated-node-index-and-kernel-def-hash.js
var require_deprecated_node_index_and_kernel_def_hash = __commonJS({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/deprecated-node-index-and-kernel-def-hash.js"(exports) {
    "use strict";
    var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = {
          enumerable: true,
          get: function() {
            return m[k];
          }
        };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    });
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    } : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function(o2) {
          var ar = [];
          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
          return ar;
        };
        return ownKeys(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DeprecatedNodeIndexAndKernelDefHash = void 0;
    var flatbuffers2 = __importStar(require_flatbuffers());
    var DeprecatedNodeIndexAndKernelDefHash2 = class _DeprecatedNodeIndexAndKernelDefHash {
      constructor() {
        this.bb = null;
        this.bb_pos = 0;
      }
      __init(i, bb) {
        this.bb_pos = i;
        this.bb = bb;
        return this;
      }
      static getRootAsDeprecatedNodeIndexAndKernelDefHash(bb, obj) {
        return (obj || new _DeprecatedNodeIndexAndKernelDefHash()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      static getSizePrefixedRootAsDeprecatedNodeIndexAndKernelDefHash(bb, obj) {
        bb.setPosition(bb.position() + flatbuffers2.SIZE_PREFIX_LENGTH);
        return (obj || new _DeprecatedNodeIndexAndKernelDefHash()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      nodeIndex() {
        const offset = this.bb.__offset(this.bb_pos, 4);
        return offset ? this.bb.readUint32(this.bb_pos + offset) : 0;
      }
      kernelDefHash() {
        const offset = this.bb.__offset(this.bb_pos, 6);
        return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt("0");
      }
      static startDeprecatedNodeIndexAndKernelDefHash(builder) {
        builder.startObject(2);
      }
      static addNodeIndex(builder, nodeIndex) {
        builder.addFieldInt32(0, nodeIndex, 0);
      }
      static addKernelDefHash(builder, kernelDefHash) {
        builder.addFieldInt64(1, kernelDefHash, BigInt("0"));
      }
      static endDeprecatedNodeIndexAndKernelDefHash(builder) {
        const offset = builder.endObject();
        return offset;
      }
      static createDeprecatedNodeIndexAndKernelDefHash(builder, nodeIndex, kernelDefHash) {
        _DeprecatedNodeIndexAndKernelDefHash.startDeprecatedNodeIndexAndKernelDefHash(builder);
        _DeprecatedNodeIndexAndKernelDefHash.addNodeIndex(builder, nodeIndex);
        _DeprecatedNodeIndexAndKernelDefHash.addKernelDefHash(builder, kernelDefHash);
        return _DeprecatedNodeIndexAndKernelDefHash.endDeprecatedNodeIndexAndKernelDefHash(builder);
      }
    };
    exports.DeprecatedNodeIndexAndKernelDefHash = DeprecatedNodeIndexAndKernelDefHash2;
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/deprecated-sub-graph-session-state.js
var require_deprecated_sub_graph_session_state = __commonJS({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/deprecated-sub-graph-session-state.js"(exports) {
    "use strict";
    var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = {
          enumerable: true,
          get: function() {
            return m[k];
          }
        };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    });
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    } : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function(o2) {
          var ar = [];
          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
          return ar;
        };
        return ownKeys(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DeprecatedSubGraphSessionState = void 0;
    var flatbuffers2 = __importStar(require_flatbuffers());
    var deprecated_session_state_js_1 = require_deprecated_session_state();
    var DeprecatedSubGraphSessionState2 = class _DeprecatedSubGraphSessionState {
      constructor() {
        this.bb = null;
        this.bb_pos = 0;
      }
      __init(i, bb) {
        this.bb_pos = i;
        this.bb = bb;
        return this;
      }
      static getRootAsDeprecatedSubGraphSessionState(bb, obj) {
        return (obj || new _DeprecatedSubGraphSessionState()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      static getSizePrefixedRootAsDeprecatedSubGraphSessionState(bb, obj) {
        bb.setPosition(bb.position() + flatbuffers2.SIZE_PREFIX_LENGTH);
        return (obj || new _DeprecatedSubGraphSessionState()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      graphId(optionalEncoding) {
        const offset = this.bb.__offset(this.bb_pos, 4);
        return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
      }
      sessionState(obj) {
        const offset = this.bb.__offset(this.bb_pos, 6);
        return offset ? (obj || new deprecated_session_state_js_1.DeprecatedSessionState()).__init(
          this.bb.__indirect(this.bb_pos + offset),
          this.bb
        ) : null;
      }
      static startDeprecatedSubGraphSessionState(builder) {
        builder.startObject(2);
      }
      static addGraphId(builder, graphIdOffset) {
        builder.addFieldOffset(0, graphIdOffset, 0);
      }
      static addSessionState(builder, sessionStateOffset) {
        builder.addFieldOffset(1, sessionStateOffset, 0);
      }
      static endDeprecatedSubGraphSessionState(builder) {
        const offset = builder.endObject();
        builder.requiredField(offset, 4);
        return offset;
      }
    };
    exports.DeprecatedSubGraphSessionState = DeprecatedSubGraphSessionState2;
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/deprecated-session-state.js
var require_deprecated_session_state = __commonJS({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/deprecated-session-state.js"(exports) {
    "use strict";
    var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = {
          enumerable: true,
          get: function() {
            return m[k];
          }
        };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    });
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    } : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function(o2) {
          var ar = [];
          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
          return ar;
        };
        return ownKeys(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DeprecatedSessionState = void 0;
    var flatbuffers2 = __importStar(require_flatbuffers());
    var deprecated_kernel_create_infos_js_1 = require_deprecated_kernel_create_infos();
    var deprecated_sub_graph_session_state_js_1 = require_deprecated_sub_graph_session_state();
    var DeprecatedSessionState2 = class _DeprecatedSessionState {
      constructor() {
        this.bb = null;
        this.bb_pos = 0;
      }
      __init(i, bb) {
        this.bb_pos = i;
        this.bb = bb;
        return this;
      }
      static getRootAsDeprecatedSessionState(bb, obj) {
        return (obj || new _DeprecatedSessionState()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      static getSizePrefixedRootAsDeprecatedSessionState(bb, obj) {
        bb.setPosition(bb.position() + flatbuffers2.SIZE_PREFIX_LENGTH);
        return (obj || new _DeprecatedSessionState()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      kernels(obj) {
        const offset = this.bb.__offset(this.bb_pos, 4);
        return offset ? (obj || new deprecated_kernel_create_infos_js_1.DeprecatedKernelCreateInfos()).__init(
          this.bb.__indirect(this.bb_pos + offset),
          this.bb
        ) : null;
      }
      subGraphSessionStates(index, obj) {
        const offset = this.bb.__offset(this.bb_pos, 6);
        return offset ? (obj || new deprecated_sub_graph_session_state_js_1.DeprecatedSubGraphSessionState()).__init(
          this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4),
          this.bb
        ) : null;
      }
      subGraphSessionStatesLength() {
        const offset = this.bb.__offset(this.bb_pos, 6);
        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
      }
      static startDeprecatedSessionState(builder) {
        builder.startObject(2);
      }
      static addKernels(builder, kernelsOffset) {
        builder.addFieldOffset(0, kernelsOffset, 0);
      }
      static addSubGraphSessionStates(builder, subGraphSessionStatesOffset) {
        builder.addFieldOffset(1, subGraphSessionStatesOffset, 0);
      }
      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();
      }
      static startSubGraphSessionStatesVector(builder, numElems) {
        builder.startVector(4, numElems, 4);
      }
      static endDeprecatedSessionState(builder) {
        const offset = builder.endObject();
        return offset;
      }
      static createDeprecatedSessionState(builder, kernelsOffset, subGraphSessionStatesOffset) {
        _DeprecatedSessionState.startDeprecatedSessionState(builder);
        _DeprecatedSessionState.addKernels(builder, kernelsOffset);
        _DeprecatedSessionState.addSubGraphSessionStates(builder, subGraphSessionStatesOffset);
        return _DeprecatedSessionState.endDeprecatedSessionState(builder);
      }
    };
    exports.DeprecatedSessionState = DeprecatedSessionState2;
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/kernel-type-str-args-entry.js
var require_kernel_type_str_args_entry = __commonJS({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/kernel-type-str-args-entry.js"(exports) {
    "use strict";
    var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = {
          enumerable: true,
          get: function() {
            return m[k];
          }
        };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    });
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    } : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function(o2) {
          var ar = [];
          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
          return ar;
        };
        return ownKeys(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.KernelTypeStrArgsEntry = void 0;
    var flatbuffers2 = __importStar(require_flatbuffers());
    var arg_type_and_index_js_1 = require_arg_type_and_index();
    var KernelTypeStrArgsEntry2 = class _KernelTypeStrArgsEntry {
      constructor() {
        this.bb = null;
        this.bb_pos = 0;
      }
      __init(i, bb) {
        this.bb_pos = i;
        this.bb = bb;
        return this;
      }
      static getRootAsKernelTypeStrArgsEntry(bb, obj) {
        return (obj || new _KernelTypeStrArgsEntry()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      static getSizePrefixedRootAsKernelTypeStrArgsEntry(bb, obj) {
        bb.setPosition(bb.position() + flatbuffers2.SIZE_PREFIX_LENGTH);
        return (obj || new _KernelTypeStrArgsEntry()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      kernelTypeStr(optionalEncoding) {
        const offset = this.bb.__offset(this.bb_pos, 4);
        return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
      }
      args(index, obj) {
        const offset = this.bb.__offset(this.bb_pos, 6);
        return offset ? (obj || new arg_type_and_index_js_1.ArgTypeAndIndex()).__init(
          this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4),
          this.bb
        ) : null;
      }
      argsLength() {
        const offset = this.bb.__offset(this.bb_pos, 6);
        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
      }
      static startKernelTypeStrArgsEntry(builder) {
        builder.startObject(2);
      }
      static addKernelTypeStr(builder, kernelTypeStrOffset) {
        builder.addFieldOffset(0, kernelTypeStrOffset, 0);
      }
      static addArgs(builder, argsOffset) {
        builder.addFieldOffset(1, argsOffset, 0);
      }
      static createArgsVector(builder, data) {
        builder.startVector(4, data.length, 4);
        for (let i = data.length - 1; i >= 0; i--) {
          builder.addOffset(data[i]);
        }
        return builder.endVector();
      }
      static startArgsVector(builder, numElems) {
        builder.startVector(4, numElems, 4);
      }
      static endKernelTypeStrArgsEntry(builder) {
        const offset = builder.endObject();
        builder.requiredField(offset, 4);
        return offset;
      }
      static createKernelTypeStrArgsEntry(builder, kernelTypeStrOffset, argsOffset) {
        _KernelTypeStrArgsEntry.startKernelTypeStrArgsEntry(builder);
        _KernelTypeStrArgsEntry.addKernelTypeStr(builder, kernelTypeStrOffset);
        _KernelTypeStrArgsEntry.addArgs(builder, argsOffset);
        return _KernelTypeStrArgsEntry.endKernelTypeStrArgsEntry(builder);
      }
    };
    exports.KernelTypeStrArgsEntry = KernelTypeStrArgsEntry2;
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/op-id-kernel-type-str-args-entry.js
var require_op_id_kernel_type_str_args_entry = __commonJS({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/op-id-kernel-type-str-args-entry.js"(exports) {
    "use strict";
    var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = {
          enumerable: true,
          get: function() {
            return m[k];
          }
        };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    });
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    } : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function(o2) {
          var ar = [];
          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
          return ar;
        };
        return ownKeys(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OpIdKernelTypeStrArgsEntry = void 0;
    var flatbuffers2 = __importStar(require_flatbuffers());
    var kernel_type_str_args_entry_js_1 = require_kernel_type_str_args_entry();
    var OpIdKernelTypeStrArgsEntry2 = class _OpIdKernelTypeStrArgsEntry {
      constructor() {
        this.bb = null;
        this.bb_pos = 0;
      }
      __init(i, bb) {
        this.bb_pos = i;
        this.bb = bb;
        return this;
      }
      static getRootAsOpIdKernelTypeStrArgsEntry(bb, obj) {
        return (obj || new _OpIdKernelTypeStrArgsEntry()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      static getSizePrefixedRootAsOpIdKernelTypeStrArgsEntry(bb, obj) {
        bb.setPosition(bb.position() + flatbuffers2.SIZE_PREFIX_LENGTH);
        return (obj || new _OpIdKernelTypeStrArgsEntry()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      opId(optionalEncoding) {
        const offset = this.bb.__offset(this.bb_pos, 4);
        return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
      }
      kernelTypeStrArgs(index, obj) {
        const offset = this.bb.__offset(this.bb_pos, 6);
        return offset ? (obj || new kernel_type_str_args_entry_js_1.KernelTypeStrArgsEntry()).__init(
          this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4),
          this.bb
        ) : null;
      }
      kernelTypeStrArgsLength() {
        const offset = this.bb.__offset(this.bb_pos, 6);
        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
      }
      static startOpIdKernelTypeStrArgsEntry(builder) {
        builder.startObject(2);
      }
      static addOpId(builder, opIdOffset) {
        builder.addFieldOffset(0, opIdOffset, 0);
      }
      static addKernelTypeStrArgs(builder, kernelTypeStrArgsOffset) {
        builder.addFieldOffset(1, kernelTypeStrArgsOffset, 0);
      }
      static createKernelTypeStrArgsVector(builder, data) {
        builder.startVector(4, data.length, 4);
        for (let i = data.length - 1; i >= 0; i--) {
          builder.addOffset(data[i]);
        }
        return builder.endVector();
      }
      static startKernelTypeStrArgsVector(builder, numElems) {
        builder.startVector(4, numElems, 4);
      }
      static endOpIdKernelTypeStrArgsEntry(builder) {
        const offset = builder.endObject();
        builder.requiredField(offset, 4);
        return offset;
      }
      static createOpIdKernelTypeStrArgsEntry(builder, opIdOffset, kernelTypeStrArgsOffset) {
        _OpIdKernelTypeStrArgsEntry.startOpIdKernelTypeStrArgsEntry(builder);
        _OpIdKernelTypeStrArgsEntry.addOpId(builder, opIdOffset);
        _OpIdKernelTypeStrArgsEntry.addKernelTypeStrArgs(builder, kernelTypeStrArgsOffset);
        return _OpIdKernelTypeStrArgsEntry.endOpIdKernelTypeStrArgsEntry(builder);
      }
    };
    exports.OpIdKernelTypeStrArgsEntry = OpIdKernelTypeStrArgsEntry2;
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/kernel-type-str-resolver.js
var require_kernel_type_str_resolver = __commonJS({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/kernel-type-str-resolver.js"(exports) {
    "use strict";
    var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = {
          enumerable: true,
          get: function() {
            return m[k];
          }
        };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    });
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    } : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function(o2) {
          var ar = [];
          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
          return ar;
        };
        return ownKeys(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.KernelTypeStrResolver = void 0;
    var flatbuffers2 = __importStar(require_flatbuffers());
    var op_id_kernel_type_str_args_entry_js_1 = require_op_id_kernel_type_str_args_entry();
    var KernelTypeStrResolver2 = class _KernelTypeStrResolver {
      constructor() {
        this.bb = null;
        this.bb_pos = 0;
      }
      __init(i, bb) {
        this.bb_pos = i;
        this.bb = bb;
        return this;
      }
      static getRootAsKernelTypeStrResolver(bb, obj) {
        return (obj || new _KernelTypeStrResolver()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      static getSizePrefixedRootAsKernelTypeStrResolver(bb, obj) {
        bb.setPosition(bb.position() + flatbuffers2.SIZE_PREFIX_LENGTH);
        return (obj || new _KernelTypeStrResolver()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      opKernelTypeStrArgs(index, obj) {
        const offset = this.bb.__offset(this.bb_pos, 4);
        return offset ? (obj || new op_id_kernel_type_str_args_entry_js_1.OpIdKernelTypeStrArgsEntry()).__init(
          this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4),
          this.bb
        ) : null;
      }
      opKernelTypeStrArgsLength() {
        const offset = this.bb.__offset(this.bb_pos, 4);
        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
      }
      static startKernelTypeStrResolver(builder) {
        builder.startObject(1);
      }
      static addOpKernelTypeStrArgs(builder, opKernelTypeStrArgsOffset) {
        builder.addFieldOffset(0, opKernelTypeStrArgsOffset, 0);
      }
      static createOpKernelTypeStrArgsVector(builder, data) {
        builder.startVector(4, data.length, 4);
        for (let i = data.length - 1; i >= 0; i--) {
          builder.addOffset(data[i]);
        }
        return builder.endVector();
      }
      static startOpKernelTypeStrArgsVector(builder, numElems) {
        builder.startVector(4, numElems, 4);
      }
      static endKernelTypeStrResolver(builder) {
        const offset = builder.endObject();
        return offset;
      }
      static createKernelTypeStrResolver(builder, opKernelTypeStrArgsOffset) {
        _KernelTypeStrResolver.startKernelTypeStrResolver(builder);
        _KernelTypeStrResolver.addOpKernelTypeStrArgs(builder, opKernelTypeStrArgsOffset);
        return _KernelTypeStrResolver.endKernelTypeStrResolver(builder);
      }
    };
    exports.KernelTypeStrResolver = KernelTypeStrResolver2;
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/operator-set-id.js
var require_operator_set_id = __commonJS({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/operator-set-id.js"(exports) {
    "use strict";
    var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = {
          enumerable: true,
          get: function() {
            return m[k];
          }
        };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    });
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    } : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function(o2) {
          var ar = [];
          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
          return ar;
        };
        return ownKeys(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.OperatorSetId = void 0;
    var flatbuffers2 = __importStar(require_flatbuffers());
    var OperatorSetId2 = class _OperatorSetId {
      constructor() {
        this.bb = null;
        this.bb_pos = 0;
      }
      __init(i, bb) {
        this.bb_pos = i;
        this.bb = bb;
        return this;
      }
      static getRootAsOperatorSetId(bb, obj) {
        return (obj || new _OperatorSetId()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      static getSizePrefixedRootAsOperatorSetId(bb, obj) {
        bb.setPosition(bb.position() + flatbuffers2.SIZE_PREFIX_LENGTH);
        return (obj || new _OperatorSetId()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      domain(optionalEncoding) {
        const offset = this.bb.__offset(this.bb_pos, 4);
        return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
      }
      version() {
        const offset = this.bb.__offset(this.bb_pos, 6);
        return offset ? this.bb.readInt64(this.bb_pos + offset) : BigInt("0");
      }
      static startOperatorSetId(builder) {
        builder.startObject(2);
      }
      static addDomain(builder, domainOffset) {
        builder.addFieldOffset(0, domainOffset, 0);
      }
      static addVersion(builder, version3) {
        builder.addFieldInt64(1, version3, BigInt("0"));
      }
      static endOperatorSetId(builder) {
        const 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);
      }
    };
    exports.OperatorSetId = OperatorSetId2;
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/string-string-entry.js
var require_string_string_entry = __commonJS({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/string-string-entry.js"(exports) {
    "use strict";
    var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = {
          enumerable: true,
          get: function() {
            return m[k];
          }
        };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    });
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    } : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function(o2) {
          var ar = [];
          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
          return ar;
        };
        return ownKeys(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.StringStringEntry = void 0;
    var flatbuffers2 = __importStar(require_flatbuffers());
    var StringStringEntry2 = class _StringStringEntry {
      constructor() {
        this.bb = null;
        this.bb_pos = 0;
      }
      __init(i, bb) {
        this.bb_pos = i;
        this.bb = bb;
        return this;
      }
      static getRootAsStringStringEntry(bb, obj) {
        return (obj || new _StringStringEntry()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      static getSizePrefixedRootAsStringStringEntry(bb, obj) {
        bb.setPosition(bb.position() + flatbuffers2.SIZE_PREFIX_LENGTH);
        return (obj || new _StringStringEntry()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      key(optionalEncoding) {
        const offset = this.bb.__offset(this.bb_pos, 4);
        return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
      }
      value(optionalEncoding) {
        const offset = this.bb.__offset(this.bb_pos, 6);
        return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
      }
      static startStringStringEntry(builder) {
        builder.startObject(2);
      }
      static addKey(builder, keyOffset) {
        builder.addFieldOffset(0, keyOffset, 0);
      }
      static addValue(builder, valueOffset) {
        builder.addFieldOffset(1, valueOffset, 0);
      }
      static endStringStringEntry(builder) {
        const offset = builder.endObject();
        return offset;
      }
      static createStringStringEntry(builder, keyOffset, valueOffset) {
        _StringStringEntry.startStringStringEntry(builder);
        _StringStringEntry.addKey(builder, keyOffset);
        _StringStringEntry.addValue(builder, valueOffset);
        return _StringStringEntry.endStringStringEntry(builder);
      }
    };
    exports.StringStringEntry = StringStringEntry2;
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/model.js
var require_model = __commonJS({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/model.js"(exports) {
    "use strict";
    var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = {
          enumerable: true,
          get: function() {
            return m[k];
          }
        };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    });
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    } : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function(o2) {
          var ar = [];
          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
          return ar;
        };
        return ownKeys(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.Model = void 0;
    var flatbuffers2 = __importStar(require_flatbuffers());
    var graph_js_1 = require_graph();
    var operator_set_id_js_1 = require_operator_set_id();
    var string_string_entry_js_1 = require_string_string_entry();
    var Model3 = class _Model {
      constructor() {
        this.bb = null;
        this.bb_pos = 0;
      }
      __init(i, bb) {
        this.bb_pos = i;
        this.bb = bb;
        return this;
      }
      static getRootAsModel(bb, obj) {
        return (obj || new _Model()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      static getSizePrefixedRootAsModel(bb, obj) {
        bb.setPosition(bb.position() + flatbuffers2.SIZE_PREFIX_LENGTH);
        return (obj || new _Model()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      irVersion() {
        const offset = this.bb.__offset(this.bb_pos, 4);
        return offset ? this.bb.readInt64(this.bb_pos + offset) : BigInt("0");
      }
      opsetImport(index, obj) {
        const offset = this.bb.__offset(this.bb_pos, 6);
        return offset ? (obj || new operator_set_id_js_1.OperatorSetId()).__init(
          this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4),
          this.bb
        ) : null;
      }
      opsetImportLength() {
        const offset = this.bb.__offset(this.bb_pos, 6);
        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
      }
      producerName(optionalEncoding) {
        const offset = this.bb.__offset(this.bb_pos, 8);
        return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
      }
      producerVersion(optionalEncoding) {
        const offset = this.bb.__offset(this.bb_pos, 10);
        return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
      }
      domain(optionalEncoding) {
        const offset = this.bb.__offset(this.bb_pos, 12);
        return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
      }
      modelVersion() {
        const offset = this.bb.__offset(this.bb_pos, 14);
        return offset ? this.bb.readInt64(this.bb_pos + offset) : BigInt("0");
      }
      docString(optionalEncoding) {
        const offset = this.bb.__offset(this.bb_pos, 16);
        return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
      }
      graph(obj) {
        const offset = this.bb.__offset(this.bb_pos, 18);
        return offset ? (obj || new graph_js_1.Graph()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null;
      }
      graphDocString(optionalEncoding) {
        const offset = this.bb.__offset(this.bb_pos, 20);
        return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
      }
      metadataProps(index, obj) {
        const offset = this.bb.__offset(this.bb_pos, 22);
        return offset ? (obj || new string_string_entry_js_1.StringStringEntry()).__init(
          this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4),
          this.bb
        ) : null;
      }
      metadataPropsLength() {
        const offset = this.bb.__offset(this.bb_pos, 22);
        return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0;
      }
      static startModel(builder) {
        builder.startObject(10);
      }
      static addIrVersion(builder, irVersion) {
        builder.addFieldInt64(0, irVersion, BigInt("0"));
      }
      static addOpsetImport(builder, opsetImportOffset) {
        builder.addFieldOffset(1, opsetImportOffset, 0);
      }
      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();
      }
      static startOpsetImportVector(builder, numElems) {
        builder.startVector(4, numElems, 4);
      }
      static addProducerName(builder, producerNameOffset) {
        builder.addFieldOffset(2, producerNameOffset, 0);
      }
      static addProducerVersion(builder, producerVersionOffset) {
        builder.addFieldOffset(3, producerVersionOffset, 0);
      }
      static addDomain(builder, domainOffset) {
        builder.addFieldOffset(4, domainOffset, 0);
      }
      static addModelVersion(builder, modelVersion) {
        builder.addFieldInt64(5, modelVersion, BigInt("0"));
      }
      static addDocString(builder, docStringOffset) {
        builder.addFieldOffset(6, docStringOffset, 0);
      }
      static addGraph(builder, graphOffset) {
        builder.addFieldOffset(7, graphOffset, 0);
      }
      static addGraphDocString(builder, graphDocStringOffset) {
        builder.addFieldOffset(8, graphDocStringOffset, 0);
      }
      static addMetadataProps(builder, metadataPropsOffset) {
        builder.addFieldOffset(9, metadataPropsOffset, 0);
      }
      static createMetadataPropsVector(builder, data) {
        builder.startVector(4, data.length, 4);
        for (let i = data.length - 1; i >= 0; i--) {
          builder.addOffset(data[i]);
        }
        return builder.endVector();
      }
      static startMetadataPropsVector(builder, numElems) {
        builder.startVector(4, numElems, 4);
      }
      static endModel(builder) {
        const offset = builder.endObject();
        return offset;
      }
    };
    exports.Model = Model3;
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/inference-session.js
var require_inference_session = __commonJS({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs/inference-session.js"(exports) {
    "use strict";
    var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = {
          enumerable: true,
          get: function() {
            return m[k];
          }
        };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    });
    var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    } : function(o, v) {
      o["default"] = v;
    });
    var __importStar = exports && exports.__importStar || /* @__PURE__ */ (function() {
      var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function(o2) {
          var ar = [];
          for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
          return ar;
        };
        return ownKeys(o);
      };
      return function(mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) {
          for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        }
        __setModuleDefault(result, mod);
        return result;
      };
    })();
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.InferenceSession = void 0;
    var flatbuffers2 = __importStar(require_flatbuffers());
    var kernel_type_str_resolver_js_1 = require_kernel_type_str_resolver();
    var model_js_1 = require_model();
    var InferenceSession5 = class _InferenceSession {
      constructor() {
        this.bb = null;
        this.bb_pos = 0;
      }
      __init(i, bb) {
        this.bb_pos = i;
        this.bb = bb;
        return this;
      }
      static getRootAsInferenceSession(bb, obj) {
        return (obj || new _InferenceSession()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      static getSizePrefixedRootAsInferenceSession(bb, obj) {
        bb.setPosition(bb.position() + flatbuffers2.SIZE_PREFIX_LENGTH);
        return (obj || new _InferenceSession()).__init(bb.readInt32(bb.position()) + bb.position(), bb);
      }
      static bufferHasIdentifier(bb) {
        return bb.__has_identifier("ORTM");
      }
      ortVersion(optionalEncoding) {
        const offset = this.bb.__offset(this.bb_pos, 4);
        return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null;
      }
      model(obj) {
        const offset = this.bb.__offset(this.bb_pos, 6);
        return offset ? (obj || new model_js_1.Model()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null;
      }
      kernelTypeStrResolver(obj) {
        const offset = this.bb.__offset(this.bb_pos, 10);
        return offset ? (obj || new kernel_type_str_resolver_js_1.KernelTypeStrResolver()).__init(
          this.bb.__indirect(this.bb_pos + offset),
          this.bb
        ) : null;
      }
      static startInferenceSession(builder) {
        builder.startObject(4);
      }
      static addOrtVersion(builder, ortVersionOffset) {
        builder.addFieldOffset(0, ortVersionOffset, 0);
      }
      static addModel(builder, modelOffset) {
        builder.addFieldOffset(1, modelOffset, 0);
      }
      static addKernelTypeStrResolver(builder, kernelTypeStrResolverOffset) {
        builder.addFieldOffset(3, kernelTypeStrResolverOffset, 0);
      }
      static endInferenceSession(builder) {
        const offset = builder.endObject();
        return offset;
      }
      static finishInferenceSessionBuffer(builder, offset) {
        builder.finish(offset, "ORTM");
      }
      static finishSizePrefixedInferenceSessionBuffer(builder, offset) {
        builder.finish(offset, "ORTM", true);
      }
    };
    exports.InferenceSession = InferenceSession5;
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs.ts
var import_arg_type, import_arg_type_and_index, import_attribute, import_attribute_type, import_deprecated_kernel_create_infos, import_deprecated_node_index_and_kernel_def_hash, import_deprecated_session_state, import_deprecated_sub_graph_session_state, import_dimension, import_dimension_value, import_dimension_value_type, import_edge_end, import_graph, import_inference_session, import_kernel_type_str_args_entry, import_kernel_type_str_resolver, import_map_type, import_model, import_node, import_node_edge, import_node_type, import_nodes_to_optimize_indices, import_op_id_kernel_type_str_args_entry, import_operator_set_id, import_runtime_optimization_record, import_runtime_optimization_record_container_entry, import_runtime_optimizations, import_sequence_type, import_shape, import_sparse_tensor, import_string_string_entry, import_tensor2, import_tensor_data_type, import_tensor_type_and_shape, import_type_info, import_type_info_value, import_value_info;
var init_fbs = __esm({
  "web/lib/onnxjs/ort-schema/flatbuffers/onnxruntime/fbs.ts"() {
    "use strict";
    import_arg_type = __toESM(require_arg_type());
    import_arg_type_and_index = __toESM(require_arg_type_and_index());
    import_attribute = __toESM(require_attribute());
    import_attribute_type = __toESM(require_attribute_type());
    import_deprecated_kernel_create_infos = __toESM(require_deprecated_kernel_create_infos());
    import_deprecated_node_index_and_kernel_def_hash = __toESM(require_deprecated_node_index_and_kernel_def_hash());
    import_deprecated_session_state = __toESM(require_deprecated_session_state());
    import_deprecated_sub_graph_session_state = __toESM(require_deprecated_sub_graph_session_state());
    import_dimension = __toESM(require_dimension());
    import_dimension_value = __toESM(require_dimension_value());
    import_dimension_value_type = __toESM(require_dimension_value_type());
    import_edge_end = __toESM(require_edge_end());
    import_graph = __toESM(require_graph());
    import_inference_session = __toESM(require_inference_session());
    import_kernel_type_str_args_entry = __toESM(require_kernel_type_str_args_entry());
    import_kernel_type_str_resolver = __toESM(require_kernel_type_str_resolver());
    import_map_type = __toESM(require_map_type());
    import_model = __toESM(require_model());
    import_node = __toESM(require_node());
    import_node_edge = __toESM(require_node_edge());
    import_node_type = __toESM(require_node_type());
    import_nodes_to_optimize_indices = __toESM(require_nodes_to_optimize_indices());
    import_op_id_kernel_type_str_args_entry = __toESM(require_op_id_kernel_type_str_args_entry());
    import_operator_set_id = __toESM(require_operator_set_id());
    import_runtime_optimization_record = __toESM(require_runtime_optimization_record());
    import_runtime_optimization_record_container_entry = __toESM(require_runtime_optimization_record_container_entry());
    import_runtime_optimizations = __toESM(require_runtime_optimizations());
    import_sequence_type = __toESM(require_sequence_type());
    import_shape = __toESM(require_shape());
    import_sparse_tensor = __toESM(require_sparse_tensor());
    import_string_string_entry = __toESM(require_string_string_entry());
    import_tensor2 = __toESM(require_tensor());
    import_tensor_data_type = __toESM(require_tensor_data_type());
    import_tensor_type_and_shape = __toESM(require_tensor_type_and_shape());
    import_type_info = __toESM(require_type_info());
    import_type_info_value = __toESM(require_type_info_value());
    import_value_info = __toESM(require_value_info());
  }
});

// web/lib/onnxjs/ort-schema/flatbuffers/ort-generated.ts
var init_ort_generated = __esm({
  "web/lib/onnxjs/ort-schema/flatbuffers/ort-generated.ts"() {
    "use strict";
    init_fbs();
  }
});

// web/node_modules/@protobufjs/aspromise/index.js
var require_aspromise = __commonJS({
  "web/node_modules/@protobufjs/aspromise/index.js"(exports, module) {
    "use strict";
    module.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"(exports) {
    "use strict";
    var base64 = exports;
    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"(exports, module) {
    "use strict";
    module.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"(exports, module) {
    "use strict";
    module.exports = factory(factory);
    function factory(exports2) {
      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];
        }
        exports2.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev;
        exports2.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];
        }
        exports2.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev;
        exports2.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);
          }
        }
        exports2.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE);
        exports2.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);
        }
        exports2.readFloatLE = readFloat_ieee754.bind(null, readUintLE);
        exports2.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];
        }
        exports2.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev;
        exports2.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];
        }
        exports2.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev;
        exports2.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);
            }
          }
        }
        exports2.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4);
        exports2.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);
        }
        exports2.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4);
        exports2.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0);
      })();
      return exports2;
    }
    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 {
        if (typeof __require !== "function") {
          return null;
        }
        var mod = __require(moduleName);
        if (mod && (mod.length || Object.keys(mod).length)) return mod;
        return null;
      } catch (err) {
        return null;
      }
    }
  }
});

// web/node_modules/@protobufjs/utf8/index.js
var require_utf8 = __commonJS({
  "web/node_modules/@protobufjs/utf8/index.js"(exports) {
    "use strict";
    var utf8 = exports;
    var replacementChar = "\uFFFD";
    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) {
      if (end - start < 1) {
        return "";
      }
      var str = "";
      for (var i = start; i < end; ) {
        var t = buffer[i++];
        if (t <= 127) {
          str += String.fromCharCode(t);
        } else if (t >= 192 && t < 224) {
          var c2 = (t & 31) << 6 | buffer[i++] & 63;
          str += c2 >= 128 ? String.fromCharCode(c2) : replacementChar;
        } else if (t >= 224 && t < 240) {
          var c3 = (t & 15) << 12 | (buffer[i++] & 63) << 6 | buffer[i++] & 63;
          str += c3 >= 2048 ? String.fromCharCode(c3) : replacementChar;
        } else if (t >= 240) {
          var t2 = (t & 7) << 18 | (buffer[i++] & 63) << 12 | (buffer[i++] & 63) << 6 | buffer[i++] & 63;
          if (t2 < 65536 || t2 > 1114111)
            str += replacementChar;
          else {
            t2 -= 65536;
            str += String.fromCharCode(55296 + (t2 >> 10));
            str += String.fromCharCode(56320 + (t2 & 1023));
          }
        }
      }
      return str;
    };
    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"(exports, module) {
    "use strict";
    module.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"(exports, module) {
    "use strict";
    module.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/long/umd/index.js
var require_umd = __commonJS({
  "web/node_modules/long/umd/index.js"(exports, module) {
    (function(global2, factory) {
      function preferDefault(exports2) {
        return exports2.default || exports2;
      }
      if (typeof define === "function" && define.amd) {
        define([], function() {
          var exports2 = {};
          factory(exports2);
          return preferDefault(exports2);
        });
      } else if (typeof exports === "object") {
        factory(exports);
        if (typeof module === "object") module.exports = preferDefault(exports);
      } else {
        (function() {
          var exports2 = {};
          factory(exports2);
          global2.Long = preferDefault(exports2);
        })();
      }
    })(
      typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : exports,
      function(_exports) {
        "use strict";
        Object.defineProperty(_exports, "__esModule", {
          value: true
        });
        _exports.default = void 0;
        var wasm2 = null;
        try {
          wasm2 = new WebAssembly.Instance(
            new WebAssembly.Module(
              new Uint8Array([
                // \0asm
                0,
                97,
                115,
                109,
                // version 1
                1,
                0,
                0,
                0,
                // section "type"
                1,
                13,
                2,
                // 0, () => i32
                96,
                0,
                1,
                127,
                // 1, (i32, i32, i32, i32) => i32
                96,
                4,
                127,
                127,
                127,
                127,
                1,
                127,
                // section "function"
                3,
                7,
                6,
                // 0, type 0
                0,
                // 1, type 1
                1,
                // 2, type 1
                1,
                // 3, type 1
                1,
                // 4, type 1
                1,
                // 5, type 1
                1,
                // section "global"
                6,
                6,
                1,
                // 0, "high", mutable i32
                127,
                1,
                65,
                0,
                11,
                // section "export"
                7,
                50,
                6,
                // 0, "mul"
                3,
                109,
                117,
                108,
                0,
                1,
                // 1, "div_s"
                5,
                100,
                105,
                118,
                95,
                115,
                0,
                2,
                // 2, "div_u"
                5,
                100,
                105,
                118,
                95,
                117,
                0,
                3,
                // 3, "rem_s"
                5,
                114,
                101,
                109,
                95,
                115,
                0,
                4,
                // 4, "rem_u"
                5,
                114,
                101,
                109,
                95,
                117,
                0,
                5,
                // 5, "get_high"
                8,
                103,
                101,
                116,
                95,
                104,
                105,
                103,
                104,
                0,
                0,
                // section "code"
                10,
                191,
                1,
                6,
                // 0, "get_high"
                4,
                0,
                35,
                0,
                11,
                // 1, "mul"
                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,
                // 2, "div_s"
                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,
                // 3, "div_u"
                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,
                // 4, "rem_s"
                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,
                // 5, "rem_u"
                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 {
        }
        function Long2(low, high, unsigned) {
          this.low = low | 0;
          this.high = high | 0;
          this.unsigned = !!unsigned;
        }
        Long2.prototype.__isLong__;
        Object.defineProperty(Long2.prototype, "__isLong__", {
          value: true
        });
        function isLong2(obj) {
          return (obj && obj["__isLong__"]) === true;
        }
        function ctz322(value) {
          var c = Math.clz32(value & -value);
          return value ? 31 - c : c;
        }
        Long2.isLong = isLong2;
        var INT_CACHE2 = {};
        var UINT_CACHE2 = {};
        function fromInt2(value, unsigned) {
          var obj, cachedObj, cache2;
          if (unsigned) {
            value >>>= 0;
            if (cache2 = 0 <= value && value < 256) {
              cachedObj = UINT_CACHE2[value];
              if (cachedObj) return cachedObj;
            }
            obj = fromBits2(value, 0, true);
            if (cache2) UINT_CACHE2[value] = obj;
            return obj;
          } else {
            value |= 0;
            if (cache2 = -128 <= value && value < 128) {
              cachedObj = INT_CACHE2[value];
              if (cachedObj) return cachedObj;
            }
            obj = fromBits2(value, value < 0 ? -1 : 0, false);
            if (cache2) INT_CACHE2[value] = obj;
            return obj;
          }
        }
        Long2.fromInt = fromInt2;
        function fromNumber2(value, unsigned) {
          if (isNaN(value)) return unsigned ? UZERO2 : ZERO2;
          if (unsigned) {
            if (value < 0) return UZERO2;
            if (value >= TWO_PWR_64_DBL2) return MAX_UNSIGNED_VALUE2;
          } else {
            if (value <= -TWO_PWR_63_DBL2) return MIN_VALUE2;
            if (value + 1 >= TWO_PWR_63_DBL2) return MAX_VALUE2;
          }
          if (value < 0) return fromNumber2(-value, unsigned).neg();
          return fromBits2(
            value % TWO_PWR_32_DBL2 | 0,
            value / TWO_PWR_32_DBL2 | 0,
            unsigned
          );
        }
        Long2.fromNumber = fromNumber2;
        function fromBits2(lowBits, highBits, unsigned) {
          return new Long2(lowBits, highBits, unsigned);
        }
        Long2.fromBits = fromBits2;
        var pow_dbl2 = Math.pow;
        function fromString2(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 ? UZERO2 : ZERO2;
          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 fromString2(str.substring(1), unsigned, radix).neg();
          }
          var radixToPower = fromNumber2(pow_dbl2(radix, 8));
          var result = ZERO2;
          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 = fromNumber2(pow_dbl2(radix, size));
              result = result.mul(power).add(fromNumber2(value));
            } else {
              result = result.mul(radixToPower);
              result = result.add(fromNumber2(value));
            }
          }
          result.unsigned = unsigned;
          return result;
        }
        Long2.fromString = fromString2;
        function fromValue2(val, unsigned) {
          if (typeof val === "number") return fromNumber2(val, unsigned);
          if (typeof val === "string") return fromString2(val, unsigned);
          return fromBits2(
            val.low,
            val.high,
            typeof unsigned === "boolean" ? unsigned : val.unsigned
          );
        }
        Long2.fromValue = fromValue2;
        var TWO_PWR_16_DBL2 = 1 << 16;
        var TWO_PWR_24_DBL2 = 1 << 24;
        var TWO_PWR_32_DBL2 = TWO_PWR_16_DBL2 * TWO_PWR_16_DBL2;
        var TWO_PWR_64_DBL2 = TWO_PWR_32_DBL2 * TWO_PWR_32_DBL2;
        var TWO_PWR_63_DBL2 = TWO_PWR_64_DBL2 / 2;
        var TWO_PWR_242 = fromInt2(TWO_PWR_24_DBL2);
        var ZERO2 = fromInt2(0);
        Long2.ZERO = ZERO2;
        var UZERO2 = fromInt2(0, true);
        Long2.UZERO = UZERO2;
        var ONE2 = fromInt2(1);
        Long2.ONE = ONE2;
        var UONE2 = fromInt2(1, true);
        Long2.UONE = UONE2;
        var NEG_ONE2 = fromInt2(-1);
        Long2.NEG_ONE = NEG_ONE2;
        var MAX_VALUE2 = fromBits2(4294967295 | 0, 2147483647 | 0, false);
        Long2.MAX_VALUE = MAX_VALUE2;
        var MAX_UNSIGNED_VALUE2 = fromBits2(4294967295 | 0, 4294967295 | 0, true);
        Long2.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE2;
        var MIN_VALUE2 = fromBits2(0, 2147483648 | 0, false);
        Long2.MIN_VALUE = MIN_VALUE2;
        var LongPrototype2 = Long2.prototype;
        LongPrototype2.toInt = function toInt2() {
          return this.unsigned ? this.low >>> 0 : this.low;
        };
        LongPrototype2.toNumber = function toNumber2() {
          if (this.unsigned)
            return (this.high >>> 0) * TWO_PWR_32_DBL2 + (this.low >>> 0);
          return this.high * TWO_PWR_32_DBL2 + (this.low >>> 0);
        };
        LongPrototype2.toString = function toString2(radix) {
          radix = radix || 10;
          if (radix < 2 || 36 < radix) throw RangeError("radix");
          if (this.isZero()) return "0";
          if (this.isNegative()) {
            if (this.eq(MIN_VALUE2)) {
              var radixLong = fromNumber2(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 = fromNumber2(pow_dbl2(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;
            }
          }
        };
        LongPrototype2.getHighBits = function getHighBits2() {
          return this.high;
        };
        LongPrototype2.getHighBitsUnsigned = function getHighBitsUnsigned2() {
          return this.high >>> 0;
        };
        LongPrototype2.getLowBits = function getLowBits2() {
          return this.low;
        };
        LongPrototype2.getLowBitsUnsigned = function getLowBitsUnsigned2() {
          return this.low >>> 0;
        };
        LongPrototype2.getNumBitsAbs = function getNumBitsAbs2() {
          if (this.isNegative())
            return this.eq(MIN_VALUE2) ? 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;
        };
        LongPrototype2.isSafeInteger = function isSafeInteger2() {
          var top11Bits = this.high >> 21;
          if (!top11Bits) return true;
          if (this.unsigned) return false;
          return top11Bits === -1 && !(this.low === 0 && this.high === -2097152);
        };
        LongPrototype2.isZero = function isZero2() {
          return this.high === 0 && this.low === 0;
        };
        LongPrototype2.eqz = LongPrototype2.isZero;
        LongPrototype2.isNegative = function isNegative2() {
          return !this.unsigned && this.high < 0;
        };
        LongPrototype2.isPositive = function isPositive2() {
          return this.unsigned || this.high >= 0;
        };
        LongPrototype2.isOdd = function isOdd2() {
          return (this.low & 1) === 1;
        };
        LongPrototype2.isEven = function isEven2() {
          return (this.low & 1) === 0;
        };
        LongPrototype2.equals = function equals2(other) {
          if (!isLong2(other)) other = fromValue2(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;
        };
        LongPrototype2.eq = LongPrototype2.equals;
        LongPrototype2.notEquals = function notEquals2(other) {
          return !this.eq(
            /* validates */
            other
          );
        };
        LongPrototype2.neq = LongPrototype2.notEquals;
        LongPrototype2.ne = LongPrototype2.notEquals;
        LongPrototype2.lessThan = function lessThan2(other) {
          return this.comp(
            /* validates */
            other
          ) < 0;
        };
        LongPrototype2.lt = LongPrototype2.lessThan;
        LongPrototype2.lessThanOrEqual = function lessThanOrEqual2(other) {
          return this.comp(
            /* validates */
            other
          ) <= 0;
        };
        LongPrototype2.lte = LongPrototype2.lessThanOrEqual;
        LongPrototype2.le = LongPrototype2.lessThanOrEqual;
        LongPrototype2.greaterThan = function greaterThan2(other) {
          return this.comp(
            /* validates */
            other
          ) > 0;
        };
        LongPrototype2.gt = LongPrototype2.greaterThan;
        LongPrototype2.greaterThanOrEqual = function greaterThanOrEqual2(other) {
          return this.comp(
            /* validates */
            other
          ) >= 0;
        };
        LongPrototype2.gte = LongPrototype2.greaterThanOrEqual;
        LongPrototype2.ge = LongPrototype2.greaterThanOrEqual;
        LongPrototype2.compare = function compare2(other) {
          if (!isLong2(other)) other = fromValue2(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;
        };
        LongPrototype2.comp = LongPrototype2.compare;
        LongPrototype2.negate = function negate2() {
          if (!this.unsigned && this.eq(MIN_VALUE2)) return MIN_VALUE2;
          return this.not().add(ONE2);
        };
        LongPrototype2.neg = LongPrototype2.negate;
        LongPrototype2.add = function add3(addend) {
          if (!isLong2(addend)) addend = fromValue2(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 fromBits2(c16 << 16 | c00, c48 << 16 | c32, this.unsigned);
        };
        LongPrototype2.subtract = function subtract2(subtrahend) {
          if (!isLong2(subtrahend)) subtrahend = fromValue2(subtrahend);
          return this.add(subtrahend.neg());
        };
        LongPrototype2.sub = LongPrototype2.subtract;
        LongPrototype2.multiply = function multiply2(multiplier) {
          if (this.isZero()) return this;
          if (!isLong2(multiplier)) multiplier = fromValue2(multiplier);
          if (wasm2) {
            var low = wasm2["mul"](
              this.low,
              this.high,
              multiplier.low,
              multiplier.high
            );
            return fromBits2(low, wasm2["get_high"](), this.unsigned);
          }
          if (multiplier.isZero()) return this.unsigned ? UZERO2 : ZERO2;
          if (this.eq(MIN_VALUE2)) return multiplier.isOdd() ? MIN_VALUE2 : ZERO2;
          if (multiplier.eq(MIN_VALUE2)) return this.isOdd() ? MIN_VALUE2 : ZERO2;
          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_242) && multiplier.lt(TWO_PWR_242))
            return fromNumber2(
              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 fromBits2(c16 << 16 | c00, c48 << 16 | c32, this.unsigned);
        };
        LongPrototype2.mul = LongPrototype2.multiply;
        LongPrototype2.divide = function divide2(divisor) {
          if (!isLong2(divisor)) divisor = fromValue2(divisor);
          if (divisor.isZero()) throw Error("division by zero");
          if (wasm2) {
            if (!this.unsigned && this.high === -2147483648 && divisor.low === -1 && divisor.high === -1) {
              return this;
            }
            var low = (this.unsigned ? wasm2["div_u"] : wasm2["div_s"])(
              this.low,
              this.high,
              divisor.low,
              divisor.high
            );
            return fromBits2(low, wasm2["get_high"](), this.unsigned);
          }
          if (this.isZero()) return this.unsigned ? UZERO2 : ZERO2;
          var approx, rem, res;
          if (!this.unsigned) {
            if (this.eq(MIN_VALUE2)) {
              if (divisor.eq(ONE2) || divisor.eq(NEG_ONE2))
                return MIN_VALUE2;
              else if (divisor.eq(MIN_VALUE2)) return ONE2;
              else {
                var halfThis = this.shr(1);
                approx = halfThis.div(divisor).shl(1);
                if (approx.eq(ZERO2)) {
                  return divisor.isNegative() ? ONE2 : NEG_ONE2;
                } else {
                  rem = this.sub(divisor.mul(approx));
                  res = approx.add(rem.div(divisor));
                  return res;
                }
              }
            } else if (divisor.eq(MIN_VALUE2)) return this.unsigned ? UZERO2 : ZERO2;
            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 = ZERO2;
          } else {
            if (!divisor.unsigned) divisor = divisor.toUnsigned();
            if (divisor.gt(this)) return UZERO2;
            if (divisor.gt(this.shru(1)))
              return UONE2;
            res = UZERO2;
          }
          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_dbl2(2, log22 - 48), approxRes = fromNumber2(approx), approxRem = approxRes.mul(divisor);
            while (approxRem.isNegative() || approxRem.gt(rem)) {
              approx -= delta;
              approxRes = fromNumber2(approx, this.unsigned);
              approxRem = approxRes.mul(divisor);
            }
            if (approxRes.isZero()) approxRes = ONE2;
            res = res.add(approxRes);
            rem = rem.sub(approxRem);
          }
          return res;
        };
        LongPrototype2.div = LongPrototype2.divide;
        LongPrototype2.modulo = function modulo2(divisor) {
          if (!isLong2(divisor)) divisor = fromValue2(divisor);
          if (wasm2) {
            var low = (this.unsigned ? wasm2["rem_u"] : wasm2["rem_s"])(
              this.low,
              this.high,
              divisor.low,
              divisor.high
            );
            return fromBits2(low, wasm2["get_high"](), this.unsigned);
          }
          return this.sub(this.div(divisor).mul(divisor));
        };
        LongPrototype2.mod = LongPrototype2.modulo;
        LongPrototype2.rem = LongPrototype2.modulo;
        LongPrototype2.not = function not3() {
          return fromBits2(~this.low, ~this.high, this.unsigned);
        };
        LongPrototype2.countLeadingZeros = function countLeadingZeros2() {
          return this.high ? Math.clz32(this.high) : Math.clz32(this.low) + 32;
        };
        LongPrototype2.clz = LongPrototype2.countLeadingZeros;
        LongPrototype2.countTrailingZeros = function countTrailingZeros2() {
          return this.low ? ctz322(this.low) : ctz322(this.high) + 32;
        };
        LongPrototype2.ctz = LongPrototype2.countTrailingZeros;
        LongPrototype2.and = function and3(other) {
          if (!isLong2(other)) other = fromValue2(other);
          return fromBits2(
            this.low & other.low,
            this.high & other.high,
            this.unsigned
          );
        };
        LongPrototype2.or = function or3(other) {
          if (!isLong2(other)) other = fromValue2(other);
          return fromBits2(
            this.low | other.low,
            this.high | other.high,
            this.unsigned
          );
        };
        LongPrototype2.xor = function xor3(other) {
          if (!isLong2(other)) other = fromValue2(other);
          return fromBits2(
            this.low ^ other.low,
            this.high ^ other.high,
            this.unsigned
          );
        };
        LongPrototype2.shiftLeft = function shiftLeft2(numBits) {
          if (isLong2(numBits)) numBits = numBits.toInt();
          if ((numBits &= 63) === 0) return this;
          else if (numBits < 32)
            return fromBits2(
              this.low << numBits,
              this.high << numBits | this.low >>> 32 - numBits,
              this.unsigned
            );
          else return fromBits2(0, this.low << numBits - 32, this.unsigned);
        };
        LongPrototype2.shl = LongPrototype2.shiftLeft;
        LongPrototype2.shiftRight = function shiftRight2(numBits) {
          if (isLong2(numBits)) numBits = numBits.toInt();
          if ((numBits &= 63) === 0) return this;
          else if (numBits < 32)
            return fromBits2(
              this.low >>> numBits | this.high << 32 - numBits,
              this.high >> numBits,
              this.unsigned
            );
          else
            return fromBits2(
              this.high >> numBits - 32,
              this.high >= 0 ? 0 : -1,
              this.unsigned
            );
        };
        LongPrototype2.shr = LongPrototype2.shiftRight;
        LongPrototype2.shiftRightUnsigned = function shiftRightUnsigned2(numBits) {
          if (isLong2(numBits)) numBits = numBits.toInt();
          if ((numBits &= 63) === 0) return this;
          if (numBits < 32)
            return fromBits2(
              this.low >>> numBits | this.high << 32 - numBits,
              this.high >>> numBits,
              this.unsigned
            );
          if (numBits === 32) return fromBits2(this.high, 0, this.unsigned);
          return fromBits2(this.high >>> numBits - 32, 0, this.unsigned);
        };
        LongPrototype2.shru = LongPrototype2.shiftRightUnsigned;
        LongPrototype2.shr_u = LongPrototype2.shiftRightUnsigned;
        LongPrototype2.rotateLeft = function rotateLeft2(numBits) {
          var b;
          if (isLong2(numBits)) numBits = numBits.toInt();
          if ((numBits &= 63) === 0) return this;
          if (numBits === 32) return fromBits2(this.high, this.low, this.unsigned);
          if (numBits < 32) {
            b = 32 - numBits;
            return fromBits2(
              this.low << numBits | this.high >>> b,
              this.high << numBits | this.low >>> b,
              this.unsigned
            );
          }
          numBits -= 32;
          b = 32 - numBits;
          return fromBits2(
            this.high << numBits | this.low >>> b,
            this.low << numBits | this.high >>> b,
            this.unsigned
          );
        };
        LongPrototype2.rotl = LongPrototype2.rotateLeft;
        LongPrototype2.rotateRight = function rotateRight2(numBits) {
          var b;
          if (isLong2(numBits)) numBits = numBits.toInt();
          if ((numBits &= 63) === 0) return this;
          if (numBits === 32) return fromBits2(this.high, this.low, this.unsigned);
          if (numBits < 32) {
            b = 32 - numBits;
            return fromBits2(
              this.high << b | this.low >>> numBits,
              this.low << b | this.high >>> numBits,
              this.unsigned
            );
          }
          numBits -= 32;
          b = 32 - numBits;
          return fromBits2(
            this.low << b | this.high >>> numBits,
            this.high << b | this.low >>> numBits,
            this.unsigned
          );
        };
        LongPrototype2.rotr = LongPrototype2.rotateRight;
        LongPrototype2.toSigned = function toSigned2() {
          if (!this.unsigned) return this;
          return fromBits2(this.low, this.high, false);
        };
        LongPrototype2.toUnsigned = function toUnsigned2() {
          if (this.unsigned) return this;
          return fromBits2(this.low, this.high, true);
        };
        LongPrototype2.toBytes = function toBytes2(le) {
          return le ? this.toBytesLE() : this.toBytesBE();
        };
        LongPrototype2.toBytesLE = function toBytesLE2() {
          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
          ];
        };
        LongPrototype2.toBytesBE = function toBytesBE2() {
          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
          ];
        };
        Long2.fromBytes = function fromBytes2(bytes, unsigned, le) {
          return le ? Long2.fromBytesLE(bytes, unsigned) : Long2.fromBytesBE(bytes, unsigned);
        };
        Long2.fromBytesLE = function fromBytesLE2(bytes, unsigned) {
          return new Long2(
            bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24,
            bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24,
            unsigned
          );
        };
        Long2.fromBytesBE = function fromBytesBE2(bytes, unsigned) {
          return new Long2(
            bytes[4] << 24 | bytes[5] << 16 | bytes[6] << 8 | bytes[7],
            bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3],
            unsigned
          );
        };
        if (typeof BigInt === "function") {
          Long2.fromBigInt = function fromBigInt(value, unsigned) {
            var lowBits = Number(BigInt.asIntN(32, value));
            var highBits = Number(BigInt.asIntN(32, value >> BigInt(32)));
            return fromBits2(lowBits, highBits, unsigned);
          };
          Long2.fromValue = function fromValueWithBigInt(value, unsigned) {
            if (typeof value === "bigint") return Long2.fromBigInt(value, unsigned);
            return fromValue2(value, unsigned);
          };
          LongPrototype2.toBigInt = function toBigInt() {
            var lowBigInt = BigInt(this.low >>> 0);
            var highBigInt = BigInt(this.unsigned ? this.high >>> 0 : this.high);
            return highBigInt << BigInt(32) | lowBigInt;
          };
        }
        var _default = _exports.default = Long2;
      }
    );
  }
});

// web/node_modules/protobufjs/src/util/minimal.js
var require_minimal = __commonJS({
  "web/node_modules/protobufjs/src/util/minimal.js"(exports) {
    "use strict";
    var util = exports;
    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 || exports;
    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.global.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 || (function() {
      try {
        var Long2 = require_umd();
        return Long2 && Long2.isLong ? Long2 : null;
      } catch (e) {
        return null;
      }
    })();
    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) {
          if (keys[i] !== "__proto__")
            dst[keys[i]] = src[keys[i]];
        }
      return dst;
    }
    util.merge = merge;
    util.recursionLimit = 100;
    util.makeProp = function makeProp(obj, key) {
      Object.defineProperty(obj, key, {
        enumerable: true,
        configurable: true,
        writable: true
      });
    };
    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"(exports, module) {
    "use strict";
    module.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"(exports, module) {
    "use strict";
    module.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"(exports, module) {
    "use strict";
    module.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 = /* @__PURE__ */ (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.recursionLimit = util.recursionLimit;
    Reader.prototype.skipType = function(wireType, depth) {
      if (depth === void 0) depth = 0;
      if (depth > Reader.recursionLimit)
        throw Error("maximum nesting depth exceeded");
      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, depth + 1);
          }
          break;
        case 5:
          this.skip(4);
          break;
        /* istanbul ignore next */
        default:
          throw Error("invalid wire type " + wireType + " at offset " + this.pos);
      }
      return this;
    };
    Reader._configure = function(BufferReader_) {
      BufferReader = BufferReader_;
      Reader.create = create();
      BufferReader._configure();
      var fn = util.Long ? "toLong" : (
        /* istanbul ignore next */
        "toNumber"
      );
      util.merge(Reader.prototype, {
        int64: function read_int64() {
          return readLongVarint.call(this)[fn](false);
        },
        uint64: function read_uint64() {
          return readLongVarint.call(this)[fn](true);
        },
        sint64: function read_sint64() {
          return readLongVarint.call(this).zzDecode()[fn](false);
        },
        fixed64: function read_fixed64() {
          return readFixed64.call(this)[fn](true);
        },
        sfixed64: function read_sfixed64() {
          return readFixed64.call(this)[fn](false);
        }
      });
    };
  }
});

// web/node_modules/protobufjs/src/reader_buffer.js
var require_reader_buffer = __commonJS({
  "web/node_modules/protobufjs/src/reader_buffer.js"(exports, module) {
    "use strict";
    module.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"(exports, module) {
    "use strict";
    module.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"(exports) {
    "use strict";
    var rpc = exports;
    rpc.Service = require_service();
  }
});

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

// web/node_modules/protobufjs/src/index-minimal.js
var require_index_minimal = __commonJS({
  "web/node_modules/protobufjs/src/index-minimal.js"(exports) {
    "use strict";
    var protobuf = exports;
    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"(exports, module) {
    "use strict";
    module.exports = require_index_minimal();
  }
});

// web/lib/onnxjs/ort-schema/protobuf/onnx.js
var require_onnx = __commonJS({
  "web/lib/onnxjs/ort-schema/protobuf/onnx.js"(exports, module) {
    "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 Dimension2(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]];
            }
          }
          Dimension2.prototype.dimValue = null;
          Dimension2.prototype.dimParam = null;
          Dimension2.prototype.denotation = "";
          var $oneOfFields;
          Object.defineProperty(Dimension2.prototype, "value", {
            get: $util.oneOfGetter($oneOfFields = ["dimValue", "dimParam"]),
            set: $util.oneOfSetter($oneOfFields)
          });
          Dimension2.create = function create(properties) {
            return new Dimension2(properties);
          };
          Dimension2.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;
          };
          Dimension2.encodeDelimited = function encodeDelimited(message, writer) {
            return this.encode(message, writer).ldelim();
          };
          Dimension2.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;
          };
          Dimension2.decodeDelimited = function decodeDelimited(reader) {
            if (!(reader instanceof $Reader)) reader = new $Reader(reader);
            return this.decode(reader, reader.uint32());
          };
          Dimension2.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;
          };
          Dimension2.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;
          };
          Dimension2.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;
          };
          Dimension2.prototype.toJSON = function toJSON() {
            return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
          };
          Dimension2.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
            if (typeUrlPrefix === void 0) {
              typeUrlPrefix = "type.googleapis.com";
            }
            return typeUrlPrefix + "/onnx.TensorShapeProto.Dimension";
          };
          return Dimension2;
        })();
        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 Tensor5(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]];
            }
          }
          Tensor5.prototype.elemType = 0;
          Tensor5.prototype.shape = null;
          Tensor5.create = function create(properties) {
            return new Tensor5(properties);
          };
          Tensor5.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;
          };
          Tensor5.encodeDelimited = function encodeDelimited(message, writer) {
            return this.encode(message, writer).ldelim();
          };
          Tensor5.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;
          };
          Tensor5.decodeDelimited = function decodeDelimited(reader) {
            if (!(reader instanceof $Reader)) reader = new $Reader(reader);
            return this.decode(reader, reader.uint32());
          };
          Tensor5.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;
          };
          Tensor5.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;
          };
          Tensor5.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;
          };
          Tensor5.prototype.toJSON = function toJSON() {
            return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
          };
          Tensor5.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
            if (typeUrlPrefix === void 0) {
              typeUrlPrefix = "type.googleapis.com";
            }
            return typeUrlPrefix + "/onnx.TypeProto.Tensor";
          };
          return Tensor5;
        })();
        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 SparseTensor2(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]];
            }
          }
          SparseTensor2.prototype.elemType = 0;
          SparseTensor2.prototype.shape = null;
          SparseTensor2.create = function create(properties) {
            return new SparseTensor2(properties);
          };
          SparseTensor2.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;
          };
          SparseTensor2.encodeDelimited = function encodeDelimited(message, writer) {
            return this.encode(message, writer).ldelim();
          };
          SparseTensor2.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;
          };
          SparseTensor2.decodeDelimited = function decodeDelimited(reader) {
            if (!(reader instanceof $Reader)) reader = new $Reader(reader);
            return this.decode(reader, reader.uint32());
          };
          SparseTensor2.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;
          };
          SparseTensor2.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;
          };
          SparseTensor2.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;
          };
          SparseTensor2.prototype.toJSON = function toJSON() {
            return this.constructor.toObject(this, $protobuf.util.toJSONOptions);
          };
          SparseTensor2.getTypeUrl = function getTypeUrl(typeUrlPrefix) {
            if (typeUrlPrefix === void 0) {
              typeUrlPrefix = "type.googleapis.com";
            }
            return typeUrlPrefix + "/onnx.TypeProto.SparseTensor";
          };
          return SparseTensor2;
        })();
        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;
    })();
    module.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_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 (at least 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 broadcast
       * @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 Tensor4(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";
          // For INT64/UINT64, reduce their value to 32-bits.
          // Should throw exception when overflow
          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 parameter to convert to a unsigned number.
      static longToNumber(n) {
        if (long_default.isLong(n)) {
          return n.toNumber();
        } else if (typeof n === "bigint") {
          return Number(n);
        }
        return n;
      }
      static isLong(n) {
        return long_default.isLong(n) || typeof n === "bigint";
      }
    };
    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(
              "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;
      }
      /**
       * normalize 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 === import_tensor_data_type.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 === import_tensor_data_type.TensorDataType.UINT32 || type === import_onnx2.onnx.TensorProto.DataType.UINT64 || type === import_tensor_data_type.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, Tensor4;
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();
    Tensor4 = 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 Tensor4(
            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;
    // TODO: adding other activations that can be fused.
    default:
      return { activationFunction: "", applyActivation: "" };
  }
  const activationName = func.name;
  const activationFunction = func.body;
  const applyActivation = `value = ${activationName}_(value);`;
  return { activationFunction, applyActivation };
}
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 Tensor4([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 coordinates (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 {
      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] && // not an initialized 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",
              `Running 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 {
              void outputTensor.data;
            }
            output.push(outputTensor);
          }
          Logger.verbose("ExecPlan", "disposing of inferenceHandler");
          inferenceHandler.dispose();
          return output;
        });
      }
    };
  }
});

// web/lib/onnxjs/attribute.ts
var import_onnx3, Attribute2;
var init_attribute = __esm({
  "web/lib/onnxjs/attribute.ts"() {
    "use strict";
    init_ort_generated();
    import_onnx3 = __toESM(require_onnx());
    init_tensor2();
    init_util();
    Attribute2 = 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 import_attribute.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 ? Tensor4.fromProto(value) : Tensor4.fromOrtTensor(value);
        }
        if (attrType === import_onnx3.onnx.AttributeProto.AttributeType.TENSORS) {
          if (attr instanceof import_onnx3.onnx.AttributeProto) {
            const tensorProtos = value;
            return tensorProtos.map((value2) => Tensor4.fromProto(value2));
          } else if (attr instanceof import_attribute.Attribute) {
            const tensorProtos = value;
            return tensorProtos.map((value2) => Tensor4.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 import_attribute_type.AttributeType.FLOAT:
            return attr.f();
          case import_attribute_type.AttributeType.INT:
            return attr.i();
          case import_attribute_type.AttributeType.STRING:
            return attr.s();
          case import_attribute_type.AttributeType.TENSOR:
            return attr.t();
          case import_attribute_type.AttributeType.GRAPH:
            return attr.g();
          case import_attribute_type.AttributeType.FLOATS:
            return attr.floatsArray();
          case import_attribute_type.AttributeType.INTS: {
            const ints = [];
            for (let i = 0; i < attr.intsLength(); i++) {
              ints.push(attr.ints(i));
            }
            return ints;
          }
          case import_attribute_type.AttributeType.STRINGS: {
            const strings = [];
            for (let i = 0; i < attr.stringsLength(); i++) {
              strings.push(attr.strings(i));
            }
            return strings;
          }
          case import_attribute_type.AttributeType.TENSORS: {
            const tensors = [];
            for (let i = 0; i < attr.tensorsLength(); i++) {
              tensors.push(attr.tensors(i));
            }
            return tensors;
          }
          // case ortFbs.AttributeType.GRAPHS:
          // TODO: Subgraph not supported yet.
          // const graphs = [];
          // for (let i = 0; i < attr.graphsLength(); i++) {
          //   graphs.push(attr.graphs(i)!);
          // }
          // return graphs;
          default:
            throw new Error(`unsupported attribute type: ${import_attribute_type.AttributeType[attr.type()]}`);
        }
      }
    };
  }
});

// web/lib/onnxjs/graph.ts
var import_onnx4, Graph2, Value, Node2, 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();
    Graph2 = {
      /**
       * 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;
      }
    };
    Node2 = class {
      constructor(_nodeProto, name2) {
        if (_nodeProto instanceof import_onnx4.onnx.NodeProto) {
          this.name = _nodeProto.name;
          this.opType = _nodeProto.opType;
          this.attributes = new Attribute2(_nodeProto.attribute);
        } else if (_nodeProto instanceof import_node.Node) {
          this.name = name2 ?? _nodeProto.name();
          this.opType = _nodeProto.opType();
          this.attributes = new Attribute2(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 import_graph.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 = Tensor4.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 Node2(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 = Tensor4.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 !== import_type_info_value.TypeInfoValue.tensor_type) {
                throw new Error("Unexpected value type for the nodeArg.");
              }
              const valueInfo = graph.nodeArgs(j).type().value(new import_tensor_type_and_shape.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 = Tensor4.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 Node2(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 = Tensor4.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 specified 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) {
          // TODO: add other activation methods
          case "Relu":
          case "Sigmoid":
          case "Clip":
            return true;
          default:
            return false;
        }
      }
      fuseConvActivationNodes() {
        for (const node of this._nodes) {
          if (node.opType === "Conv") {
            const next = this._allData[node.outputs[0]]._to;
            if (next.length === 1 && this.isActivation(this._nodes[next[0]])) {
              const child = this._nodes[next[0]];
              if (child.opType === "Clip") {
                if (child.inputs.length === 1) {
                  try {
                    node.attributes.set("activation_params", "floats", [
                      child.attributes.getFloat("min"),
                      child.attributes.getFloat("max")
                    ]);
                  } catch {
                    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 flatbuffers, import_onnx5, Model2;
var init_model = __esm({
  "web/lib/onnxjs/model.ts"() {
    "use strict";
    flatbuffers = __toESM(require_flatbuffers());
    init_graph();
    init_ort_generated();
    import_onnx5 = __toESM(require_onnx());
    init_util();
    Model2 = 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 = Graph2.from(modelProto.graph, graphInitializer);
      }
      loadFromOrtFormat(buf, graphInitializer) {
        const fb = new flatbuffers.ByteBuffer(buf);
        const ortModel = import_inference_session.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 = Graph2.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_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 Model2();
          if (typeof arg === "string") {
            const isOrtFormat = arg.endsWith(".ort");
            if (false) {
              const { readFile } = null;
              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;
      }
      get inputMetadata() {
        throw new Error("Getting model metadata is not supported in webgl backend.");
      }
      get outputMetadata() {
        throw new Error("Getting model metadata is not supported in webgl backend.");
      }
      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 Tensor4(
                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();
  }
});

// web/lib/index.ts
init_esm();
init_esm();
init_esm();

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

// web/lib/index.ts
var index_default = esm_exports;
if (true) {
  const onnxjsBackend2 = (init_backend_onnxjs(), __toCommonJS(backend_onnxjs_exports)).onnxjsBackend;
  registerBackend("webgl", onnxjsBackend2, -10);
}
if (false) {
  throw new Error(
    "The current build is specified to enable both JSEP and WebGPU EP. This is not a valid configuration. JSEP and WebGPU EPs cannot be enabled at the same time."
  );
}
if (false) {
  throw new Error(
    "The current build is specified to enable WebNN EP without JSEP or WebGPU EP. This is not a valid configuration. WebNN EP requires either JSEP or WebGPU EP to be enabled."
  );
}
if (false) {
  const wasmBackend = null.wasmBackend;
  if (false) {
    registerBackend("webgpu", wasmBackend, 5);
  }
  if (false) {
    registerBackend("webnn", wasmBackend, 5);
  }
  registerBackend("cpu", wasmBackend, 10);
  registerBackend("wasm", wasmBackend, 10);
}
Object.defineProperty(env2.versions, "web", { value: version2, enumerable: true });
export {
  InferenceSession2 as InferenceSession,
  TRACE,
  TRACE_EVENT_BEGIN,
  TRACE_EVENT_END,
  TRACE_FUNC_BEGIN,
  TRACE_FUNC_END,
  Tensor2 as Tensor,
  index_default as default,
  env2 as env,
  registerBackend
};
/*! Bundled license information:

long/index.js:
long/umd/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, 2514568 characters]
