var background = (function() {
  "use strict";var __defProp2 = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __reflectGet = Reflect.get;
var __knownSymbol = (name2, symbol2) => (symbol2 = Symbol[name2]) ? symbol2 : /* @__PURE__ */ Symbol.for("Symbol." + name2);
var __typeError = (msg) => {
  throw TypeError(msg);
};
var __pow = Math.pow;
var __defNormalProp2 = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
  for (var prop in b || (b = {}))
    if (__hasOwnProp.call(b, prop))
      __defNormalProp2(a, prop, b[prop]);
  if (__getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(b)) {
      if (__propIsEnum.call(b, prop))
        __defNormalProp2(a, prop, b[prop]);
    }
  return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __objRest = (source, exclude) => {
  var target = {};
  for (var prop in source)
    if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
      target[prop] = source[prop];
  if (source != null && __getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(source)) {
      if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
        target[prop] = source[prop];
    }
  return target;
};
var __publicField2 = (obj, key, value) => __defNormalProp2(obj, typeof key !== "symbol" ? key + "" : key, value);
var __superGet = (cls, obj, key) => __reflectGet(__getProtoOf(cls), key, obj);
var __async = (__this, __arguments, generator) => {
  return new Promise((resolve2, reject) => {
    var fulfilled = (value) => {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    };
    var rejected = (value) => {
      try {
        step(generator.throw(value));
      } catch (e) {
        reject(e);
      }
    };
    var step = (x) => x.done ? resolve2(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
    step((generator = generator.apply(__this, __arguments)).next());
  });
};
var __await = function(promise2, isYieldStar) {
  this[0] = promise2;
  this[1] = isYieldStar;
};
var __asyncGenerator = (__this, __arguments, generator) => {
  var resume = (k, v, yes, no2) => {
    try {
      var x = generator[k](v), isAwait = (v = x.value) instanceof __await, done = x.done;
      Promise.resolve(isAwait ? v[0] : v).then((y) => isAwait ? resume(k === "return" ? k : "next", v[1] ? { done: y.done, value: y.value } : y, yes, no2) : yes({ value: y, done })).catch((e) => resume("throw", e, yes, no2));
    } catch (e) {
      no2(e);
    }
  }, method = (k) => it2[k] = (x) => new Promise((yes, no2) => resume(k, x, yes, no2)), it2 = {};
  return generator = generator.apply(__this, __arguments), it2[__knownSymbol("asyncIterator")] = () => it2, method("next"), method("throw"), method("return"), it2;
};
var __yieldStar = (value) => {
  var obj = value[__knownSymbol("asyncIterator")], isAwait = false, method, it2 = {};
  if (obj == null) {
    obj = value[__knownSymbol("iterator")]();
    method = (k) => it2[k] = (x) => obj[k](x);
  } else {
    obj = obj.call(value);
    method = (k) => it2[k] = (v) => {
      if (isAwait) {
        isAwait = false;
        if (k === "throw") throw v;
        return v;
      }
      isAwait = true;
      return {
        done: false,
        value: new __await(new Promise((resolve2) => {
          var x = obj[k](v);
          if (!(x instanceof Object)) __typeError("Object expected");
          resolve2(x);
        }), 1)
      };
    };
  }
  return it2[__knownSymbol("iterator")] = () => it2, method("next"), "throw" in obj ? method("throw") : it2.throw = (x) => {
    throw x;
  }, "return" in obj && method("return"), it2;
};

  var _a2, _b, _c, _d;
  function _mergeNamespaces(n, m) {
    for (var i2 = 0; i2 < m.length; i2++) {
      const e = m[i2];
      if (typeof e !== "string" && !Array.isArray(e)) {
        for (const k in e) {
          if (k !== "default" && !(k in n)) {
            const d = Object.getOwnPropertyDescriptor(e, k);
            if (d) {
              Object.defineProperty(n, k, d.get ? d : {
                enumerable: true,
                get: () => e[k]
              });
            }
          }
        }
      }
    }
    return Object.freeze(Object.defineProperty(n, Symbol.toStringTag, { value: "Module" }));
  }
  function defineBackground(arg) {
    if (arg == null || typeof arg === "function") return { main: arg };
    return arg;
  }
  const browser$2 = ((_b = (_a2 = globalThis.browser) == null ? void 0 : _a2.runtime) == null ? void 0 : _b.id) ? globalThis.browser : globalThis.chrome;
  const browser$1 = browser$2;
  function success$1(message, meta2) {
    return {
      content: [{ type: "text", text: message }],
      isError: false,
      _meta: meta2
    };
  }
  function error$J(message, code2, details) {
    return {
      content: [{ type: "text", text: message }],
      isError: true,
      _meta: __spreadValues({ code: code2 }, details)
    };
  }
  function multiContent(content, meta2) {
    return {
      content,
      isError: false,
      _meta: meta2
    };
  }
  class WebSocketEventHandler {
    constructor(websocket) {
      __publicField2(this, "websocket");
      this.websocket = websocket;
    }
    /**
     * 处理事件消息
     */
    handleEvent(message) {
      return __async(this, null, function* () {
        const eventType = message.event || message.type;
        try {
          let response;
          if (eventType === "TAB_ACTIVATE") {
            console.log("[WebSocket Event] 收到事件:", eventType, message);
            response = yield this.handleTabActivate(__spreadProps(__spreadValues({}, message.data), {
              sessionId: message.sessionId
            }));
          } else if (eventType === "SESSION_STATUS_CHANGED") {
            console.log("[WebSocket Event] 收到事件:", eventType, message);
            yield this.handleSessionStatusUpdate(message);
            return;
          } else {
            console.warn("[WebSocket Event] 未知事件类型:", eventType);
            response = {
              success: false,
              error: `Unknown event type: ${eventType}`
            };
          }
          if (message.requestId && response) {
            this.sendResponse(__spreadProps(__spreadValues({}, response), {
              requestId: message.requestId
            }));
          }
        } catch (error2) {
          console.error("[WebSocket Event] 处理事件失败:", error2);
          if (message.requestId) {
            this.sendResponse({
              requestId: message.requestId,
              success: false,
              error: error2 instanceof Error ? error2.message : String(error2)
            });
          }
        }
      });
    }
    /**
     * 处理 TAB_ACTIVATE 事件
     * 激活指定的 tab 到前台
     */
    handleTabActivate(data) {
      return __async(this, null, function* () {
        const { tabId, sessionId } = data;
        let numericTabId = typeof tabId === "string" ? parseInt(tabId.replace(/^tab_activate-/, ""), 10) : tabId;
        console.log(`[WebSocket Event] 尝试激活 tab: ${numericTabId}, sessionId: ${sessionId}`);
        try {
          let tab;
          if (!isNaN(numericTabId) && numericTabId) {
            try {
              tab = yield chrome.tabs.get(numericTabId);
            } catch (e) {
              console.warn(`[WebSocket Event] 直接获取 Tab ${numericTabId} 失败:`, e);
            }
          }
          if (!tab && sessionId) {
            console.log(`[WebSocket Event] 尝试通过 Session ${sessionId} 找最新的 Tab`);
            const { getSessionManager: getSessionManager2 } = yield Promise.resolve().then(() => index$2);
            const sessionManager = getSessionManager2();
            const session = yield sessionManager.getSession(sessionId);
            if (session && session.tabs && session.tabs.length > 0) {
              const latestSessionTab = [...session.tabs].sort(
                (a, b) => b.lastAccessedAt - a.lastAccessedAt
              )[0];
              if (latestSessionTab) {
                try {
                  tab = yield chrome.tabs.get(latestSessionTab.tabId);
                  if (tab) {
                    numericTabId = latestSessionTab.tabId;
                    console.log(`[WebSocket Event] 从 Session 找到最新的有效 Tab: ${numericTabId}`);
                  }
                } catch (e) {
                  console.warn(`[WebSocket Event] Session 中的 Tab ${latestSessionTab.tabId} 也失效了`);
                }
              }
            }
          }
          if (!tab) {
            throw new Error(
              `Tab not found and no fallback available. tabId: ${tabId}, sessionId: ${sessionId}`
            );
          }
          if (tab.windowId) {
            yield chrome.windows.update(tab.windowId, { focused: true });
          }
          yield chrome.tabs.update(tab.id, { active: true });
          console.log(`[WebSocket Event] Tab ${tab.id} 已激活`);
          return {
            success: true,
            data: {
              tabId: tab.id,
              url: tab.url,
              title: tab.title,
              windowId: tab.windowId
            }
          };
        } catch (error2) {
          console.error("[WebSocket Event] 激活 tab 失败:", error2);
          throw error2;
        }
      });
    }
    /**
     * 处理后端推送的 Session 状态变更
     */
    handleSessionStatusUpdate(pushMessage) {
      return __async(this, null, function* () {
        console.log("[WebSocket Event] 收到状态推送:", pushMessage);
        const { sessionId, data, timestamp } = pushMessage;
        const { oldStatus, newStatus } = data;
        const { getSessionManager: getSessionManager2 } = yield Promise.resolve().then(() => index$2);
        const sessionManager = getSessionManager2();
        yield sessionManager.handleStatusPush(sessionId, oldStatus, newStatus, timestamp);
      });
    }
    /**
     * 发送响应消息
     */
    sendResponse(response) {
      if (this.websocket.readyState === WebSocket.OPEN) {
        this.websocket.send(
          JSON.stringify(__spreadValues({
            type: "event_response"
          }, response))
        );
        console.log("[WebSocket Event] 发送响应:", response);
      } else {
        console.warn("[WebSocket Event] WebSocket 未连接，无法发送响应");
      }
    }
  }
  class WebSocketTransport {
    constructor(websocket) {
      __publicField2(this, "websocket");
      __publicField2(this, "eventHandler");
      __publicField2(this, "onmessage");
      __publicField2(this, "onclose");
      __publicField2(this, "onerror");
      this.websocket = websocket;
      this.eventHandler = new WebSocketEventHandler(websocket);
      console.log("[WebSocket Transport] 初始化，WebSocket 状态:", websocket == null ? void 0 : websocket.readyState);
      this.setupWebSocketHandlers();
    }
    setupWebSocketHandlers() {
      this.websocket.addEventListener("message", (event) => {
        if (event.data === "ping" || event.data === "pong") {
          return;
        }
        try {
          const message = JSON.parse(event.data);
          if (message.type === "ping") {
            this.websocket.send(JSON.stringify({ id: message.id, type: "pong" }));
            return;
          }
          if (message.type === "error") {
            if (String(message == null ? void 0 : message.status) === "401") {
              console.error("[WebSocket Transport] 401未授权错误，清空设备配置");
              chrome.storage.local.remove(["device_config"]).catch(console.error);
              chrome.storage.local.set({
                last_auth_error: {
                  status: "401",
                  message: (message == null ? void 0 : message.message) || "认证失败",
                  timestamp: Date.now()
                }
              }).catch(console.error);
              return;
            }
          }
          if (message.event || message.type) {
            this.eventHandler.handleEvent(message).catch((error2) => {
              console.error("[WebSocket Transport] 事件处理失败:", error2);
            });
            return;
          }
          if (this.onmessage) {
            try {
              this.onmessage(message);
            } catch (error2) {
              console.error("[WebSocket Transport] MCP 消息处理器抛出异常:", error2);
              if (this.onerror) {
                this.onerror(error2 instanceof Error ? error2 : new Error(String(error2)));
              }
            }
          } else {
            console.error("[WebSocket Transport] MCP 消息处理器未设置!");
          }
        } catch (error2) {
          console.error("[WebSocket Transport] 消息解析失败:", error2, "原始数据:", event.data);
          if (this.onerror) {
            this.onerror(new Error(`消息解析失败: ${error2}`));
          }
        }
      });
      this.websocket.onclose = (event) => {
        console.log("[WebSocket Transport] WebSocket 连接关闭:", event.code);
        if (this.onclose) {
          this.onclose();
        }
      };
      this.websocket.onerror = (event) => {
        console.error("[WebSocket Transport] WebSocket 错误:", event);
        if (this.onerror) {
          this.onerror(new Error("WebSocket 连接错误"));
        }
      };
    }
    start() {
      return __async(this, null, function* () {
        console.log("[WebSocket Transport] 启动完成");
      });
    }
    send(message) {
      return __async(this, null, function* () {
        if (this.websocket.readyState === WebSocket.OPEN) {
          console.debug("[WebSocket Transport] 发送消息:", message);
          this.websocket.send(JSON.stringify(message));
        } else {
          throw new Error("WebSocket 未连接");
        }
      });
    }
    close() {
      return __async(this, null, function* () {
        if (this.websocket.readyState === WebSocket.OPEN) {
          this.websocket.close();
        }
      });
    }
  }
  const NEVER = Object.freeze({
    status: "aborted"
  });
  function $constructor(name2, initializer2, params) {
    var _a3;
    function init(inst, def) {
      if (!inst._zod) {
        Object.defineProperty(inst, "_zod", {
          value: {
            def,
            constr: _,
            traits: /* @__PURE__ */ new Set()
          },
          enumerable: false
        });
      }
      if (inst._zod.traits.has(name2)) {
        return;
      }
      inst._zod.traits.add(name2);
      initializer2(inst, def);
      const proto = _.prototype;
      const keys = Object.keys(proto);
      for (let i2 = 0; i2 < keys.length; i2++) {
        const k = keys[i2];
        if (!(k in inst)) {
          inst[k] = proto[k].bind(inst);
        }
      }
    }
    const Parent = (_a3 = params == null ? void 0 : params.Parent) != null ? _a3 : Object;
    class Definition extends Parent {
    }
    Object.defineProperty(Definition, "name", { value: name2 });
    function _(def) {
      var _a5;
      var _a4;
      const inst = (params == null ? void 0 : params.Parent) ? new Definition() : this;
      init(inst, def);
      (_a5 = (_a4 = inst._zod).deferred) != null ? _a5 : _a4.deferred = [];
      for (const fn of inst._zod.deferred) {
        fn();
      }
      return inst;
    }
    Object.defineProperty(_, "init", { value: init });
    Object.defineProperty(_, Symbol.hasInstance, {
      value: (inst) => {
        var _a4, _b2;
        if ((params == null ? void 0 : params.Parent) && inst instanceof params.Parent)
          return true;
        return (_b2 = (_a4 = inst == null ? void 0 : inst._zod) == null ? void 0 : _a4.traits) == null ? void 0 : _b2.has(name2);
      }
    });
    Object.defineProperty(_, "name", { value: name2 });
    return _;
  }
  const $brand = /* @__PURE__ */ Symbol("zod_brand");
  class $ZodAsyncError extends Error {
    constructor() {
      super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
    }
  }
  class $ZodEncodeError extends Error {
    constructor(name2) {
      super(`Encountered unidirectional transform during encode: ${name2}`);
      this.name = "ZodEncodeError";
    }
  }
  const globalConfig = {};
  function config(newConfig) {
    if (newConfig)
      Object.assign(globalConfig, newConfig);
    return globalConfig;
  }
  function assertEqual(val) {
    return val;
  }
  function assertNotEqual(val) {
    return val;
  }
  function assertIs(_arg) {
  }
  function assertNever(_x) {
    throw new Error("Unexpected value in exhaustive check");
  }
  function assert(_) {
  }
  function getEnumValues(entries) {
    const numericValues = Object.values(entries).filter((v) => typeof v === "number");
    const values = Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v);
    return values;
  }
  function joinValues(array2, separator = "|") {
    return array2.map((val) => stringifyPrimitive(val)).join(separator);
  }
  function jsonStringifyReplacer(_, value) {
    if (typeof value === "bigint")
      return value.toString();
    return value;
  }
  function cached(getter) {
    return {
      get value() {
        {
          const value = getter();
          Object.defineProperty(this, "value", { value });
          return value;
        }
      }
    };
  }
  function nullish$1(input) {
    return input === null || input === void 0;
  }
  function cleanRegex(source) {
    const start = source.startsWith("^") ? 1 : 0;
    const end = source.endsWith("$") ? source.length - 1 : source.length;
    return source.slice(start, end);
  }
  function floatSafeRemainder(val, step) {
    const valDecCount = (val.toString().split(".")[1] || "").length;
    const stepString = step.toString();
    let stepDecCount = (stepString.split(".")[1] || "").length;
    if (stepDecCount === 0 && /\d?e-\d?/.test(stepString)) {
      const match = stepString.match(/\d?e-(\d?)/);
      if (match == null ? void 0 : match[1]) {
        stepDecCount = Number.parseInt(match[1]);
      }
    }
    const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
    const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
    const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
    return valInt % stepInt / __pow(10, decCount);
  }
  const EVALUATING = /* @__PURE__ */ Symbol("evaluating");
  function defineLazy(object2, key, getter) {
    let value = void 0;
    Object.defineProperty(object2, key, {
      get() {
        if (value === EVALUATING) {
          return void 0;
        }
        if (value === void 0) {
          value = EVALUATING;
          value = getter();
        }
        return value;
      },
      set(v) {
        Object.defineProperty(object2, key, {
          value: v
          // configurable: true,
        });
      },
      configurable: true
    });
  }
  function objectClone(obj) {
    return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));
  }
  function assignProp(target, prop, value) {
    Object.defineProperty(target, prop, {
      value,
      writable: true,
      enumerable: true,
      configurable: true
    });
  }
  function mergeDefs(...defs) {
    const mergedDescriptors = {};
    for (const def of defs) {
      const descriptors = Object.getOwnPropertyDescriptors(def);
      Object.assign(mergedDescriptors, descriptors);
    }
    return Object.defineProperties({}, mergedDescriptors);
  }
  function cloneDef(schema) {
    return mergeDefs(schema._zod.def);
  }
  function getElementAtPath(obj, path) {
    if (!path)
      return obj;
    return path.reduce((acc, key) => acc == null ? void 0 : acc[key], obj);
  }
  function promiseAllObject(promisesObj) {
    const keys = Object.keys(promisesObj);
    const promises = keys.map((key) => promisesObj[key]);
    return Promise.all(promises).then((results) => {
      const resolvedObj = {};
      for (let i2 = 0; i2 < keys.length; i2++) {
        resolvedObj[keys[i2]] = results[i2];
      }
      return resolvedObj;
    });
  }
  function randomString(length = 10) {
    const chars = "abcdefghijklmnopqrstuvwxyz";
    let str = "";
    for (let i2 = 0; i2 < length; i2++) {
      str += chars[Math.floor(Math.random() * chars.length)];
    }
    return str;
  }
  function esc(str) {
    return JSON.stringify(str);
  }
  function slugify(input) {
    return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
  }
  const captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {
  };
  function isObject(data) {
    return typeof data === "object" && data !== null && !Array.isArray(data);
  }
  const allowsEval = cached(() => {
    var _a3;
    if (typeof navigator !== "undefined" && ((_a3 = navigator == null ? void 0 : navigator.userAgent) == null ? void 0 : _a3.includes("Cloudflare"))) {
      return false;
    }
    try {
      const F = Function;
      new F("");
      return true;
    } catch (_) {
      return false;
    }
  });
  function isPlainObject$1(o) {
    if (isObject(o) === false)
      return false;
    const ctor = o.constructor;
    if (ctor === void 0)
      return true;
    if (typeof ctor !== "function")
      return true;
    const prot = ctor.prototype;
    if (isObject(prot) === false)
      return false;
    if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) {
      return false;
    }
    return true;
  }
  function shallowClone(o) {
    if (isPlainObject$1(o))
      return __spreadValues({}, o);
    if (Array.isArray(o))
      return [...o];
    return o;
  }
  function numKeys(data) {
    let keyCount = 0;
    for (const key in data) {
      if (Object.prototype.hasOwnProperty.call(data, key)) {
        keyCount++;
      }
    }
    return keyCount;
  }
  const getParsedType = (data) => {
    const t = typeof data;
    switch (t) {
      case "undefined":
        return "undefined";
      case "string":
        return "string";
      case "number":
        return Number.isNaN(data) ? "nan" : "number";
      case "boolean":
        return "boolean";
      case "function":
        return "function";
      case "bigint":
        return "bigint";
      case "symbol":
        return "symbol";
      case "object":
        if (Array.isArray(data)) {
          return "array";
        }
        if (data === null) {
          return "null";
        }
        if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
          return "promise";
        }
        if (typeof Map !== "undefined" && data instanceof Map) {
          return "map";
        }
        if (typeof Set !== "undefined" && data instanceof Set) {
          return "set";
        }
        if (typeof Date !== "undefined" && data instanceof Date) {
          return "date";
        }
        if (typeof File !== "undefined" && data instanceof File) {
          return "file";
        }
        return "object";
      default:
        throw new Error(`Unknown data type: ${t}`);
    }
  };
  const propertyKeyTypes = /* @__PURE__ */ new Set(["string", "number", "symbol"]);
  const primitiveTypes = /* @__PURE__ */ new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]);
  function escapeRegex(str) {
    return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  }
  function clone(inst, def, params) {
    const cl = new inst._zod.constr(def != null ? def : inst._zod.def);
    if (!def || (params == null ? void 0 : params.parent))
      cl._zod.parent = inst;
    return cl;
  }
  function normalizeParams(_params) {
    const params = _params;
    if (!params)
      return {};
    if (typeof params === "string")
      return { error: () => params };
    if ((params == null ? void 0 : params.message) !== void 0) {
      if ((params == null ? void 0 : params.error) !== void 0)
        throw new Error("Cannot specify both `message` and `error` params");
      params.error = params.message;
    }
    delete params.message;
    if (typeof params.error === "string")
      return __spreadProps(__spreadValues({}, params), { error: () => params.error });
    return params;
  }
  function createTransparentProxy(getter) {
    let target;
    return new Proxy({}, {
      get(_, prop, receiver) {
        target != null ? target : target = getter();
        return Reflect.get(target, prop, receiver);
      },
      set(_, prop, value, receiver) {
        target != null ? target : target = getter();
        return Reflect.set(target, prop, value, receiver);
      },
      has(_, prop) {
        target != null ? target : target = getter();
        return Reflect.has(target, prop);
      },
      deleteProperty(_, prop) {
        target != null ? target : target = getter();
        return Reflect.deleteProperty(target, prop);
      },
      ownKeys(_) {
        target != null ? target : target = getter();
        return Reflect.ownKeys(target);
      },
      getOwnPropertyDescriptor(_, prop) {
        target != null ? target : target = getter();
        return Reflect.getOwnPropertyDescriptor(target, prop);
      },
      defineProperty(_, prop, descriptor) {
        target != null ? target : target = getter();
        return Reflect.defineProperty(target, prop, descriptor);
      }
    });
  }
  function stringifyPrimitive(value) {
    if (typeof value === "bigint")
      return value.toString() + "n";
    if (typeof value === "string")
      return `"${value}"`;
    return `${value}`;
  }
  function optionalKeys(shape) {
    return Object.keys(shape).filter((k) => {
      return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional";
    });
  }
  const NUMBER_FORMAT_RANGES = {
    safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
    int32: [-2147483648, 2147483647],
    uint32: [0, 4294967295],
    float32: [-34028234663852886e22, 34028234663852886e22],
    float64: [-Number.MAX_VALUE, Number.MAX_VALUE]
  };
  const BIGINT_FORMAT_RANGES = {
    int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")],
    uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")]
  };
  function pick(schema, mask) {
    const currDef = schema._zod.def;
    const def = mergeDefs(schema._zod.def, {
      get shape() {
        const newShape = {};
        for (const key in mask) {
          if (!(key in currDef.shape)) {
            throw new Error(`Unrecognized key: "${key}"`);
          }
          if (!mask[key])
            continue;
          newShape[key] = currDef.shape[key];
        }
        assignProp(this, "shape", newShape);
        return newShape;
      },
      checks: []
    });
    return clone(schema, def);
  }
  function omit(schema, mask) {
    const currDef = schema._zod.def;
    const def = mergeDefs(schema._zod.def, {
      get shape() {
        const newShape = __spreadValues({}, schema._zod.def.shape);
        for (const key in mask) {
          if (!(key in currDef.shape)) {
            throw new Error(`Unrecognized key: "${key}"`);
          }
          if (!mask[key])
            continue;
          delete newShape[key];
        }
        assignProp(this, "shape", newShape);
        return newShape;
      },
      checks: []
    });
    return clone(schema, def);
  }
  function extend(schema, shape) {
    if (!isPlainObject$1(shape)) {
      throw new Error("Invalid input to extend: expected a plain object");
    }
    const checks = schema._zod.def.checks;
    const hasChecks = checks && checks.length > 0;
    if (hasChecks) {
      throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");
    }
    const def = mergeDefs(schema._zod.def, {
      get shape() {
        const _shape = __spreadValues(__spreadValues({}, schema._zod.def.shape), shape);
        assignProp(this, "shape", _shape);
        return _shape;
      },
      checks: []
    });
    return clone(schema, def);
  }
  function safeExtend(schema, shape) {
    if (!isPlainObject$1(shape)) {
      throw new Error("Invalid input to safeExtend: expected a plain object");
    }
    const def = __spreadProps(__spreadValues({}, schema._zod.def), {
      get shape() {
        const _shape = __spreadValues(__spreadValues({}, schema._zod.def.shape), shape);
        assignProp(this, "shape", _shape);
        return _shape;
      },
      checks: schema._zod.def.checks
    });
    return clone(schema, def);
  }
  function merge(a, b) {
    const def = mergeDefs(a._zod.def, {
      get shape() {
        const _shape = __spreadValues(__spreadValues({}, a._zod.def.shape), b._zod.def.shape);
        assignProp(this, "shape", _shape);
        return _shape;
      },
      get catchall() {
        return b._zod.def.catchall;
      },
      checks: []
      // delete existing checks
    });
    return clone(a, def);
  }
  function partial(Class2, schema, mask) {
    const def = mergeDefs(schema._zod.def, {
      get shape() {
        const oldShape = schema._zod.def.shape;
        const shape = __spreadValues({}, oldShape);
        if (mask) {
          for (const key in mask) {
            if (!(key in oldShape)) {
              throw new Error(`Unrecognized key: "${key}"`);
            }
            if (!mask[key])
              continue;
            shape[key] = Class2 ? new Class2({
              type: "optional",
              innerType: oldShape[key]
            }) : oldShape[key];
          }
        } else {
          for (const key in oldShape) {
            shape[key] = Class2 ? new Class2({
              type: "optional",
              innerType: oldShape[key]
            }) : oldShape[key];
          }
        }
        assignProp(this, "shape", shape);
        return shape;
      },
      checks: []
    });
    return clone(schema, def);
  }
  function required$2(Class2, schema, mask) {
    const def = mergeDefs(schema._zod.def, {
      get shape() {
        const oldShape = schema._zod.def.shape;
        const shape = __spreadValues({}, oldShape);
        if (mask) {
          for (const key in mask) {
            if (!(key in shape)) {
              throw new Error(`Unrecognized key: "${key}"`);
            }
            if (!mask[key])
              continue;
            shape[key] = new Class2({
              type: "nonoptional",
              innerType: oldShape[key]
            });
          }
        } else {
          for (const key in oldShape) {
            shape[key] = new Class2({
              type: "nonoptional",
              innerType: oldShape[key]
            });
          }
        }
        assignProp(this, "shape", shape);
        return shape;
      },
      checks: []
    });
    return clone(schema, def);
  }
  function aborted(x, startIndex = 0) {
    var _a3;
    if (x.aborted === true)
      return true;
    for (let i2 = startIndex; i2 < x.issues.length; i2++) {
      if (((_a3 = x.issues[i2]) == null ? void 0 : _a3.continue) !== true) {
        return true;
      }
    }
    return false;
  }
  function prefixIssues(path, issues) {
    return issues.map((iss) => {
      var _a4;
      var _a3;
      (_a4 = (_a3 = iss).path) != null ? _a4 : _a3.path = [];
      iss.path.unshift(path);
      return iss;
    });
  }
  function unwrapMessage(message) {
    return typeof message === "string" ? message : message == null ? void 0 : message.message;
  }
  function finalizeIssue(iss, ctx, config2) {
    var _a3, _b2, _c2, _d2, _e, _f, _g, _h, _i, _j, _k;
    const full = __spreadProps(__spreadValues({}, iss), { path: (_a3 = iss.path) != null ? _a3 : [] });
    if (!iss.message) {
      const message = (_k = (_j = (_h = (_f = unwrapMessage((_d2 = (_c2 = (_b2 = iss.inst) == null ? void 0 : _b2._zod.def) == null ? void 0 : _c2.error) == null ? void 0 : _d2.call(_c2, iss))) != null ? _f : unwrapMessage((_e = ctx == null ? void 0 : ctx.error) == null ? void 0 : _e.call(ctx, iss))) != null ? _h : unwrapMessage((_g = config2.customError) == null ? void 0 : _g.call(config2, iss))) != null ? _j : unwrapMessage((_i = config2.localeError) == null ? void 0 : _i.call(config2, iss))) != null ? _k : "Invalid input";
      full.message = message;
    }
    delete full.inst;
    delete full.continue;
    if (!(ctx == null ? void 0 : ctx.reportInput)) {
      delete full.input;
    }
    return full;
  }
  function getSizableOrigin(input) {
    if (input instanceof Set)
      return "set";
    if (input instanceof Map)
      return "map";
    if (input instanceof File)
      return "file";
    return "unknown";
  }
  function getLengthableOrigin(input) {
    if (Array.isArray(input))
      return "array";
    if (typeof input === "string")
      return "string";
    return "unknown";
  }
  function issue(...args) {
    const [iss, input, inst] = args;
    if (typeof iss === "string") {
      return {
        message: iss,
        code: "custom",
        input,
        inst
      };
    }
    return __spreadValues({}, iss);
  }
  function cleanEnum(obj) {
    return Object.entries(obj).filter(([k, _]) => {
      return Number.isNaN(Number.parseInt(k, 10));
    }).map((el) => el[1]);
  }
  function base64ToUint8Array(base642) {
    const binaryString = atob(base642);
    const bytes = new Uint8Array(binaryString.length);
    for (let i2 = 0; i2 < binaryString.length; i2++) {
      bytes[i2] = binaryString.charCodeAt(i2);
    }
    return bytes;
  }
  function uint8ArrayToBase64(bytes) {
    let binaryString = "";
    for (let i2 = 0; i2 < bytes.length; i2++) {
      binaryString += String.fromCharCode(bytes[i2]);
    }
    return btoa(binaryString);
  }
  function base64urlToUint8Array(base64url2) {
    const base642 = base64url2.replace(/-/g, "+").replace(/_/g, "/");
    const padding = "=".repeat((4 - base642.length % 4) % 4);
    return base64ToUint8Array(base642 + padding);
  }
  function uint8ArrayToBase64url(bytes) {
    return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
  }
  function hexToUint8Array(hex2) {
    const cleanHex = hex2.replace(/^0x/, "");
    if (cleanHex.length % 2 !== 0) {
      throw new Error("Invalid hex string length");
    }
    const bytes = new Uint8Array(cleanHex.length / 2);
    for (let i2 = 0; i2 < cleanHex.length; i2 += 2) {
      bytes[i2 / 2] = Number.parseInt(cleanHex.slice(i2, i2 + 2), 16);
    }
    return bytes;
  }
  function uint8ArrayToHex(bytes) {
    return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
  }
  class Class {
    constructor(..._args) {
    }
  }
  const util$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
    __proto__: null,
    BIGINT_FORMAT_RANGES,
    Class,
    NUMBER_FORMAT_RANGES,
    aborted,
    allowsEval,
    assert,
    assertEqual,
    assertIs,
    assertNever,
    assertNotEqual,
    assignProp,
    base64ToUint8Array,
    base64urlToUint8Array,
    cached,
    captureStackTrace,
    cleanEnum,
    cleanRegex,
    clone,
    cloneDef,
    createTransparentProxy,
    defineLazy,
    esc,
    escapeRegex,
    extend,
    finalizeIssue,
    floatSafeRemainder,
    getElementAtPath,
    getEnumValues,
    getLengthableOrigin,
    getParsedType,
    getSizableOrigin,
    hexToUint8Array,
    isObject,
    isPlainObject: isPlainObject$1,
    issue,
    joinValues,
    jsonStringifyReplacer,
    merge,
    mergeDefs,
    normalizeParams,
    nullish: nullish$1,
    numKeys,
    objectClone,
    omit,
    optionalKeys,
    partial,
    pick,
    prefixIssues,
    primitiveTypes,
    promiseAllObject,
    propertyKeyTypes,
    randomString,
    required: required$2,
    safeExtend,
    shallowClone,
    slugify,
    stringifyPrimitive,
    uint8ArrayToBase64,
    uint8ArrayToBase64url,
    uint8ArrayToHex,
    unwrapMessage
  }, Symbol.toStringTag, { value: "Module" }));
  const initializer$1 = (inst, def) => {
    inst.name = "$ZodError";
    Object.defineProperty(inst, "_zod", {
      value: inst._zod,
      enumerable: false
    });
    Object.defineProperty(inst, "issues", {
      value: def,
      enumerable: false
    });
    inst.message = JSON.stringify(def, jsonStringifyReplacer, 2);
    Object.defineProperty(inst, "toString", {
      value: () => inst.message,
      enumerable: false
    });
  };
  const $ZodError = $constructor("$ZodError", initializer$1);
  const $ZodRealError = $constructor("$ZodError", initializer$1, { Parent: Error });
  function flattenError(error2, mapper = (issue2) => issue2.message) {
    const fieldErrors = {};
    const formErrors = [];
    for (const sub of error2.issues) {
      if (sub.path.length > 0) {
        fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
        fieldErrors[sub.path[0]].push(mapper(sub));
      } else {
        formErrors.push(mapper(sub));
      }
    }
    return { formErrors, fieldErrors };
  }
  function formatError(error2, mapper = (issue2) => issue2.message) {
    const fieldErrors = { _errors: [] };
    const processError = (error3) => {
      for (const issue2 of error3.issues) {
        if (issue2.code === "invalid_union" && issue2.errors.length) {
          issue2.errors.map((issues) => processError({ issues }));
        } else if (issue2.code === "invalid_key") {
          processError({ issues: issue2.issues });
        } else if (issue2.code === "invalid_element") {
          processError({ issues: issue2.issues });
        } else if (issue2.path.length === 0) {
          fieldErrors._errors.push(mapper(issue2));
        } else {
          let curr = fieldErrors;
          let i2 = 0;
          while (i2 < issue2.path.length) {
            const el = issue2.path[i2];
            const terminal = i2 === issue2.path.length - 1;
            if (!terminal) {
              curr[el] = curr[el] || { _errors: [] };
            } else {
              curr[el] = curr[el] || { _errors: [] };
              curr[el]._errors.push(mapper(issue2));
            }
            curr = curr[el];
            i2++;
          }
        }
      }
    };
    processError(error2);
    return fieldErrors;
  }
  function treeifyError(error2, mapper = (issue2) => issue2.message) {
    const result2 = { errors: [] };
    const processError = (error3, path = []) => {
      var _a4, _b3, _c2, _d2;
      var _a3, _b2;
      for (const issue2 of error3.issues) {
        if (issue2.code === "invalid_union" && issue2.errors.length) {
          issue2.errors.map((issues) => processError({ issues }, issue2.path));
        } else if (issue2.code === "invalid_key") {
          processError({ issues: issue2.issues }, issue2.path);
        } else if (issue2.code === "invalid_element") {
          processError({ issues: issue2.issues }, issue2.path);
        } else {
          const fullpath = [...path, ...issue2.path];
          if (fullpath.length === 0) {
            result2.errors.push(mapper(issue2));
            continue;
          }
          let curr = result2;
          let i2 = 0;
          while (i2 < fullpath.length) {
            const el = fullpath[i2];
            const terminal = i2 === fullpath.length - 1;
            if (typeof el === "string") {
              (_a4 = curr.properties) != null ? _a4 : curr.properties = {};
              (_b3 = (_a3 = curr.properties)[el]) != null ? _b3 : _a3[el] = { errors: [] };
              curr = curr.properties[el];
            } else {
              (_c2 = curr.items) != null ? _c2 : curr.items = [];
              (_d2 = (_b2 = curr.items)[el]) != null ? _d2 : _b2[el] = { errors: [] };
              curr = curr.items[el];
            }
            if (terminal) {
              curr.errors.push(mapper(issue2));
            }
            i2++;
          }
        }
      }
    };
    processError(error2);
    return result2;
  }
  function toDotPath(_path) {
    const segs = [];
    const path = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
    for (const seg of path) {
      if (typeof seg === "number")
        segs.push(`[${seg}]`);
      else if (typeof seg === "symbol")
        segs.push(`[${JSON.stringify(String(seg))}]`);
      else if (/[^\w$]/.test(seg))
        segs.push(`[${JSON.stringify(seg)}]`);
      else {
        if (segs.length)
          segs.push(".");
        segs.push(seg);
      }
    }
    return segs.join("");
  }
  function prettifyError(error2) {
    var _a3;
    const lines = [];
    const issues = [...error2.issues].sort((a, b) => {
      var _a4, _b2;
      return ((_a4 = a.path) != null ? _a4 : []).length - ((_b2 = b.path) != null ? _b2 : []).length;
    });
    for (const issue2 of issues) {
      lines.push(`✖ ${issue2.message}`);
      if ((_a3 = issue2.path) == null ? void 0 : _a3.length)
        lines.push(`  → at ${toDotPath(issue2.path)}`);
    }
    return lines.join("\n");
  }
  const _parse = (_Err) => (schema, value, _ctx, _params) => {
    var _a3;
    const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };
    const result2 = schema._zod.run({ value, issues: [] }, ctx);
    if (result2 instanceof Promise) {
      throw new $ZodAsyncError();
    }
    if (result2.issues.length) {
      const e = new ((_a3 = _params == null ? void 0 : _params.Err) != null ? _a3 : _Err)(result2.issues.map((iss) => finalizeIssue(iss, ctx, config())));
      captureStackTrace(e, _params == null ? void 0 : _params.callee);
      throw e;
    }
    return result2.value;
  };
  const parse$1 = /* @__PURE__ */ _parse($ZodRealError);
  const _parseAsync = (_Err) => (schema, value, _ctx, params) => __async(null, null, function* () {
    var _a3;
    const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
    let result2 = schema._zod.run({ value, issues: [] }, ctx);
    if (result2 instanceof Promise)
      result2 = yield result2;
    if (result2.issues.length) {
      const e = new ((_a3 = params == null ? void 0 : params.Err) != null ? _a3 : _Err)(result2.issues.map((iss) => finalizeIssue(iss, ctx, config())));
      captureStackTrace(e, params == null ? void 0 : params.callee);
      throw e;
    }
    return result2.value;
  });
  const parseAsync$1 = /* @__PURE__ */ _parseAsync($ZodRealError);
  const _safeParse = (_Err) => (schema, value, _ctx) => {
    const ctx = _ctx ? __spreadProps(__spreadValues({}, _ctx), { async: false }) : { async: false };
    const result2 = schema._zod.run({ value, issues: [] }, ctx);
    if (result2 instanceof Promise) {
      throw new $ZodAsyncError();
    }
    return result2.issues.length ? {
      success: false,
      error: new (_Err != null ? _Err : $ZodError)(result2.issues.map((iss) => finalizeIssue(iss, ctx, config())))
    } : { success: true, data: result2.value };
  };
  const safeParse$2 = /* @__PURE__ */ _safeParse($ZodRealError);
  const _safeParseAsync = (_Err) => (schema, value, _ctx) => __async(null, null, function* () {
    const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
    let result2 = schema._zod.run({ value, issues: [] }, ctx);
    if (result2 instanceof Promise)
      result2 = yield result2;
    return result2.issues.length ? {
      success: false,
      error: new _Err(result2.issues.map((iss) => finalizeIssue(iss, ctx, config())))
    } : { success: true, data: result2.value };
  });
  const safeParseAsync$1 = /* @__PURE__ */ _safeParseAsync($ZodRealError);
  const _encode = (_Err) => (schema, value, _ctx) => {
    const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
    return _parse(_Err)(schema, value, ctx);
  };
  const encode$1 = /* @__PURE__ */ _encode($ZodRealError);
  const _decode = (_Err) => (schema, value, _ctx) => {
    return _parse(_Err)(schema, value, _ctx);
  };
  const decode$1 = /* @__PURE__ */ _decode($ZodRealError);
  const _encodeAsync = (_Err) => (schema, value, _ctx) => __async(null, null, function* () {
    const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
    return _parseAsync(_Err)(schema, value, ctx);
  });
  const encodeAsync$1 = /* @__PURE__ */ _encodeAsync($ZodRealError);
  const _decodeAsync = (_Err) => (schema, value, _ctx) => __async(null, null, function* () {
    return _parseAsync(_Err)(schema, value, _ctx);
  });
  const decodeAsync$1 = /* @__PURE__ */ _decodeAsync($ZodRealError);
  const _safeEncode = (_Err) => (schema, value, _ctx) => {
    const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
    return _safeParse(_Err)(schema, value, ctx);
  };
  const safeEncode$1 = /* @__PURE__ */ _safeEncode($ZodRealError);
  const _safeDecode = (_Err) => (schema, value, _ctx) => {
    return _safeParse(_Err)(schema, value, _ctx);
  };
  const safeDecode$1 = /* @__PURE__ */ _safeDecode($ZodRealError);
  const _safeEncodeAsync = (_Err) => (schema, value, _ctx) => __async(null, null, function* () {
    const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
    return _safeParseAsync(_Err)(schema, value, ctx);
  });
  const safeEncodeAsync$1 = /* @__PURE__ */ _safeEncodeAsync($ZodRealError);
  const _safeDecodeAsync = (_Err) => (schema, value, _ctx) => __async(null, null, function* () {
    return _safeParseAsync(_Err)(schema, value, _ctx);
  });
  const safeDecodeAsync$1 = /* @__PURE__ */ _safeDecodeAsync($ZodRealError);
  const cuid$1 = /^[cC][^\s-]{8,}$/;
  const cuid2$1 = /^[0-9a-z]+$/;
  const ulid$1 = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
  const xid$1 = /^[0-9a-vA-V]{20}$/;
  const ksuid$1 = /^[A-Za-z0-9]{27}$/;
  const nanoid$2 = /^[a-zA-Z0-9_-]{21}$/;
  const duration$1 = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
  const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
  const guid$1 = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
  const uuid$1 = (version2) => {
    if (!version2)
      return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
    return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
  };
  const uuid4 = /* @__PURE__ */ uuid$1(4);
  const uuid6 = /* @__PURE__ */ uuid$1(6);
  const uuid7 = /* @__PURE__ */ uuid$1(7);
  const email$1 = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
  const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
  const rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  const unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u;
  const idnEmail = unicodeEmail;
  const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
  const _emoji$1 = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
  function emoji$1() {
    return new RegExp(_emoji$1, "u");
  }
  const ipv4$1 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
  const ipv6$1 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;
  const mac$1 = (delimiter) => {
    const escapedDelim = escapeRegex(delimiter != null ? delimiter : ":");
    return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);
  };
  const cidrv4$1 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;
  const cidrv6$1 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
  const base64$1 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
  const base64url$1 = /^[A-Za-z0-9_-]*$/;
  const hostname$1 = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/;
  const domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;
  const e164$1 = /^\+(?:[0-9]){6,14}[0-9]$/;
  const dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;
  const date$3 = /* @__PURE__ */ new RegExp(`^${dateSource}$`);
  function timeSource(args) {
    const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
    const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
    return regex;
  }
  function time$1(args) {
    return new RegExp(`^${timeSource(args)}$`);
  }
  function datetime$1(args) {
    const time2 = timeSource({ precision: args.precision });
    const opts = ["Z"];
    if (args.local)
      opts.push("");
    if (args.offset)
      opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);
    const timeRegex = `${time2}(?:${opts.join("|")})`;
    return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
  }
  const string$2 = (params) => {
    var _a3, _b2;
    const regex = params ? `[\\s\\S]{${(_a3 = params == null ? void 0 : params.minimum) != null ? _a3 : 0},${(_b2 = params == null ? void 0 : params.maximum) != null ? _b2 : ""}}` : `[\\s\\S]*`;
    return new RegExp(`^${regex}$`);
  };
  const bigint$2 = /^-?\d+n?$/;
  const integer = /^-?\d+$/;
  const number$2 = /^-?\d+(?:\.\d+)?/;
  const boolean$2 = /^(?:true|false)$/i;
  const _null$2 = /^null$/i;
  const _undefined$2 = /^undefined$/i;
  const lowercase = /^[^A-Z]*$/;
  const uppercase = /^[^a-z]*$/;
  const hex$1 = /^[0-9a-fA-F]*$/;
  function fixedBase64(bodyLength, padding) {
    return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);
  }
  function fixedBase64url(length) {
    return new RegExp(`^[A-Za-z0-9_-]{${length}}$`);
  }
  const md5_hex = /^[0-9a-fA-F]{32}$/;
  const md5_base64 = /* @__PURE__ */ fixedBase64(22, "==");
  const md5_base64url = /* @__PURE__ */ fixedBase64url(22);
  const sha1_hex = /^[0-9a-fA-F]{40}$/;
  const sha1_base64 = /* @__PURE__ */ fixedBase64(27, "=");
  const sha1_base64url = /* @__PURE__ */ fixedBase64url(27);
  const sha256_hex = /^[0-9a-fA-F]{64}$/;
  const sha256_base64 = /* @__PURE__ */ fixedBase64(43, "=");
  const sha256_base64url = /* @__PURE__ */ fixedBase64url(43);
  const sha384_hex = /^[0-9a-fA-F]{96}$/;
  const sha384_base64 = /* @__PURE__ */ fixedBase64(64, "");
  const sha384_base64url = /* @__PURE__ */ fixedBase64url(64);
  const sha512_hex = /^[0-9a-fA-F]{128}$/;
  const sha512_base64 = /* @__PURE__ */ fixedBase64(86, "==");
  const sha512_base64url = /* @__PURE__ */ fixedBase64url(86);
  const regexes = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
    __proto__: null,
    base64: base64$1,
    base64url: base64url$1,
    bigint: bigint$2,
    boolean: boolean$2,
    browserEmail,
    cidrv4: cidrv4$1,
    cidrv6: cidrv6$1,
    cuid: cuid$1,
    cuid2: cuid2$1,
    date: date$3,
    datetime: datetime$1,
    domain,
    duration: duration$1,
    e164: e164$1,
    email: email$1,
    emoji: emoji$1,
    extendedDuration,
    guid: guid$1,
    hex: hex$1,
    hostname: hostname$1,
    html5Email,
    idnEmail,
    integer,
    ipv4: ipv4$1,
    ipv6: ipv6$1,
    ksuid: ksuid$1,
    lowercase,
    mac: mac$1,
    md5_base64,
    md5_base64url,
    md5_hex,
    nanoid: nanoid$2,
    null: _null$2,
    number: number$2,
    rfc5322Email,
    sha1_base64,
    sha1_base64url,
    sha1_hex,
    sha256_base64,
    sha256_base64url,
    sha256_hex,
    sha384_base64,
    sha384_base64url,
    sha384_hex,
    sha512_base64,
    sha512_base64url,
    sha512_hex,
    string: string$2,
    time: time$1,
    ulid: ulid$1,
    undefined: _undefined$2,
    unicodeEmail,
    uppercase,
    uuid: uuid$1,
    uuid4,
    uuid6,
    uuid7,
    xid: xid$1
  }, Symbol.toStringTag, { value: "Module" }));
  const $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => {
    var _a4, _b2;
    var _a3;
    (_a4 = inst._zod) != null ? _a4 : inst._zod = {};
    inst._zod.def = def;
    (_b2 = (_a3 = inst._zod).onattach) != null ? _b2 : _a3.onattach = [];
  });
  const numericOriginMap = {
    number: "number",
    bigint: "bigint",
    object: "date"
  };
  const $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => {
    $ZodCheck.init(inst, def);
    const origin = numericOriginMap[typeof def.value];
    inst._zod.onattach.push((inst2) => {
      var _a3;
      const bag = inst2._zod.bag;
      const curr = (_a3 = def.inclusive ? bag.maximum : bag.exclusiveMaximum) != null ? _a3 : Number.POSITIVE_INFINITY;
      if (def.value < curr) {
        if (def.inclusive)
          bag.maximum = def.value;
        else
          bag.exclusiveMaximum = def.value;
      }
    });
    inst._zod.check = (payload) => {
      if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {
        return;
      }
      payload.issues.push({
        origin,
        code: "too_big",
        maximum: def.value,
        input: payload.value,
        inclusive: def.inclusive,
        inst,
        continue: !def.abort
      });
    };
  });
  const $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => {
    $ZodCheck.init(inst, def);
    const origin = numericOriginMap[typeof def.value];
    inst._zod.onattach.push((inst2) => {
      var _a3;
      const bag = inst2._zod.bag;
      const curr = (_a3 = def.inclusive ? bag.minimum : bag.exclusiveMinimum) != null ? _a3 : Number.NEGATIVE_INFINITY;
      if (def.value > curr) {
        if (def.inclusive)
          bag.minimum = def.value;
        else
          bag.exclusiveMinimum = def.value;
      }
    });
    inst._zod.check = (payload) => {
      if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {
        return;
      }
      payload.issues.push({
        origin,
        code: "too_small",
        minimum: def.value,
        input: payload.value,
        inclusive: def.inclusive,
        inst,
        continue: !def.abort
      });
    };
  });
  const $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => {
    $ZodCheck.init(inst, def);
    inst._zod.onattach.push((inst2) => {
      var _a4;
      var _a3;
      (_a4 = (_a3 = inst2._zod.bag).multipleOf) != null ? _a4 : _a3.multipleOf = def.value;
    });
    inst._zod.check = (payload) => {
      if (typeof payload.value !== typeof def.value)
        throw new Error("Cannot mix number and bigint in multiple_of check.");
      const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0;
      if (isMultiple)
        return;
      payload.issues.push({
        origin: typeof payload.value,
        code: "not_multiple_of",
        divisor: def.value,
        input: payload.value,
        inst,
        continue: !def.abort
      });
    };
  });
  const $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => {
    var _a3;
    $ZodCheck.init(inst, def);
    def.format = def.format || "float64";
    const isInt = (_a3 = def.format) == null ? void 0 : _a3.includes("int");
    const origin = isInt ? "int" : "number";
    const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format];
    inst._zod.onattach.push((inst2) => {
      const bag = inst2._zod.bag;
      bag.format = def.format;
      bag.minimum = minimum;
      bag.maximum = maximum;
      if (isInt)
        bag.pattern = integer;
    });
    inst._zod.check = (payload) => {
      const input = payload.value;
      if (isInt) {
        if (!Number.isInteger(input)) {
          payload.issues.push({
            expected: origin,
            format: def.format,
            code: "invalid_type",
            continue: false,
            input,
            inst
          });
          return;
        }
        if (!Number.isSafeInteger(input)) {
          if (input > 0) {
            payload.issues.push({
              input,
              code: "too_big",
              maximum: Number.MAX_SAFE_INTEGER,
              note: "Integers must be within the safe integer range.",
              inst,
              origin,
              continue: !def.abort
            });
          } else {
            payload.issues.push({
              input,
              code: "too_small",
              minimum: Number.MIN_SAFE_INTEGER,
              note: "Integers must be within the safe integer range.",
              inst,
              origin,
              continue: !def.abort
            });
          }
          return;
        }
      }
      if (input < minimum) {
        payload.issues.push({
          origin: "number",
          input,
          code: "too_small",
          minimum,
          inclusive: true,
          inst,
          continue: !def.abort
        });
      }
      if (input > maximum) {
        payload.issues.push({
          origin: "number",
          input,
          code: "too_big",
          maximum,
          inst
        });
      }
    };
  });
  const $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat", (inst, def) => {
    $ZodCheck.init(inst, def);
    const [minimum, maximum] = BIGINT_FORMAT_RANGES[def.format];
    inst._zod.onattach.push((inst2) => {
      const bag = inst2._zod.bag;
      bag.format = def.format;
      bag.minimum = minimum;
      bag.maximum = maximum;
    });
    inst._zod.check = (payload) => {
      const input = payload.value;
      if (input < minimum) {
        payload.issues.push({
          origin: "bigint",
          input,
          code: "too_small",
          minimum,
          inclusive: true,
          inst,
          continue: !def.abort
        });
      }
      if (input > maximum) {
        payload.issues.push({
          origin: "bigint",
          input,
          code: "too_big",
          maximum,
          inst
        });
      }
    };
  });
  const $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, def) => {
    var _a4;
    var _a3;
    $ZodCheck.init(inst, def);
    (_a4 = (_a3 = inst._zod.def).when) != null ? _a4 : _a3.when = (payload) => {
      const val = payload.value;
      return !nullish$1(val) && val.size !== void 0;
    };
    inst._zod.onattach.push((inst2) => {
      var _a5;
      const curr = (_a5 = inst2._zod.bag.maximum) != null ? _a5 : Number.POSITIVE_INFINITY;
      if (def.maximum < curr)
        inst2._zod.bag.maximum = def.maximum;
    });
    inst._zod.check = (payload) => {
      const input = payload.value;
      const size = input.size;
      if (size <= def.maximum)
        return;
      payload.issues.push({
        origin: getSizableOrigin(input),
        code: "too_big",
        maximum: def.maximum,
        inclusive: true,
        input,
        inst,
        continue: !def.abort
      });
    };
  });
  const $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, def) => {
    var _a4;
    var _a3;
    $ZodCheck.init(inst, def);
    (_a4 = (_a3 = inst._zod.def).when) != null ? _a4 : _a3.when = (payload) => {
      const val = payload.value;
      return !nullish$1(val) && val.size !== void 0;
    };
    inst._zod.onattach.push((inst2) => {
      var _a5;
      const curr = (_a5 = inst2._zod.bag.minimum) != null ? _a5 : Number.NEGATIVE_INFINITY;
      if (def.minimum > curr)
        inst2._zod.bag.minimum = def.minimum;
    });
    inst._zod.check = (payload) => {
      const input = payload.value;
      const size = input.size;
      if (size >= def.minimum)
        return;
      payload.issues.push({
        origin: getSizableOrigin(input),
        code: "too_small",
        minimum: def.minimum,
        inclusive: true,
        input,
        inst,
        continue: !def.abort
      });
    };
  });
  const $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (inst, def) => {
    var _a4;
    var _a3;
    $ZodCheck.init(inst, def);
    (_a4 = (_a3 = inst._zod.def).when) != null ? _a4 : _a3.when = (payload) => {
      const val = payload.value;
      return !nullish$1(val) && val.size !== void 0;
    };
    inst._zod.onattach.push((inst2) => {
      const bag = inst2._zod.bag;
      bag.minimum = def.size;
      bag.maximum = def.size;
      bag.size = def.size;
    });
    inst._zod.check = (payload) => {
      const input = payload.value;
      const size = input.size;
      if (size === def.size)
        return;
      const tooBig = size > def.size;
      payload.issues.push(__spreadProps(__spreadValues({
        origin: getSizableOrigin(input)
      }, tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }), {
        inclusive: true,
        exact: true,
        input: payload.value,
        inst,
        continue: !def.abort
      }));
    };
  });
  const $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => {
    var _a4;
    var _a3;
    $ZodCheck.init(inst, def);
    (_a4 = (_a3 = inst._zod.def).when) != null ? _a4 : _a3.when = (payload) => {
      const val = payload.value;
      return !nullish$1(val) && val.length !== void 0;
    };
    inst._zod.onattach.push((inst2) => {
      var _a5;
      const curr = (_a5 = inst2._zod.bag.maximum) != null ? _a5 : Number.POSITIVE_INFINITY;
      if (def.maximum < curr)
        inst2._zod.bag.maximum = def.maximum;
    });
    inst._zod.check = (payload) => {
      const input = payload.value;
      const length = input.length;
      if (length <= def.maximum)
        return;
      const origin = getLengthableOrigin(input);
      payload.issues.push({
        origin,
        code: "too_big",
        maximum: def.maximum,
        inclusive: true,
        input,
        inst,
        continue: !def.abort
      });
    };
  });
  const $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => {
    var _a4;
    var _a3;
    $ZodCheck.init(inst, def);
    (_a4 = (_a3 = inst._zod.def).when) != null ? _a4 : _a3.when = (payload) => {
      const val = payload.value;
      return !nullish$1(val) && val.length !== void 0;
    };
    inst._zod.onattach.push((inst2) => {
      var _a5;
      const curr = (_a5 = inst2._zod.bag.minimum) != null ? _a5 : Number.NEGATIVE_INFINITY;
      if (def.minimum > curr)
        inst2._zod.bag.minimum = def.minimum;
    });
    inst._zod.check = (payload) => {
      const input = payload.value;
      const length = input.length;
      if (length >= def.minimum)
        return;
      const origin = getLengthableOrigin(input);
      payload.issues.push({
        origin,
        code: "too_small",
        minimum: def.minimum,
        inclusive: true,
        input,
        inst,
        continue: !def.abort
      });
    };
  });
  const $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => {
    var _a4;
    var _a3;
    $ZodCheck.init(inst, def);
    (_a4 = (_a3 = inst._zod.def).when) != null ? _a4 : _a3.when = (payload) => {
      const val = payload.value;
      return !nullish$1(val) && val.length !== void 0;
    };
    inst._zod.onattach.push((inst2) => {
      const bag = inst2._zod.bag;
      bag.minimum = def.length;
      bag.maximum = def.length;
      bag.length = def.length;
    });
    inst._zod.check = (payload) => {
      const input = payload.value;
      const length = input.length;
      if (length === def.length)
        return;
      const origin = getLengthableOrigin(input);
      const tooBig = length > def.length;
      payload.issues.push(__spreadProps(__spreadValues({
        origin
      }, tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }), {
        inclusive: true,
        exact: true,
        input: payload.value,
        inst,
        continue: !def.abort
      }));
    };
  });
  const $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => {
    var _a4, _b3;
    var _a3, _b2;
    $ZodCheck.init(inst, def);
    inst._zod.onattach.push((inst2) => {
      var _a5;
      const bag = inst2._zod.bag;
      bag.format = def.format;
      if (def.pattern) {
        (_a5 = bag.patterns) != null ? _a5 : bag.patterns = /* @__PURE__ */ new Set();
        bag.patterns.add(def.pattern);
      }
    });
    if (def.pattern)
      (_a4 = (_a3 = inst._zod).check) != null ? _a4 : _a3.check = (payload) => {
        def.pattern.lastIndex = 0;
        if (def.pattern.test(payload.value))
          return;
        payload.issues.push(__spreadProps(__spreadValues({
          origin: "string",
          code: "invalid_format",
          format: def.format,
          input: payload.value
        }, def.pattern ? { pattern: def.pattern.toString() } : {}), {
          inst,
          continue: !def.abort
        }));
      };
    else
      (_b3 = (_b2 = inst._zod).check) != null ? _b3 : _b2.check = () => {
      };
  });
  const $ZodCheckRegex = /* @__PURE__ */ $constructor("$ZodCheckRegex", (inst, def) => {
    $ZodCheckStringFormat.init(inst, def);
    inst._zod.check = (payload) => {
      def.pattern.lastIndex = 0;
      if (def.pattern.test(payload.value))
        return;
      payload.issues.push({
        origin: "string",
        code: "invalid_format",
        format: "regex",
        input: payload.value,
        pattern: def.pattern.toString(),
        inst,
        continue: !def.abort
      });
    };
  });
  const $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => {
    var _a3;
    (_a3 = def.pattern) != null ? _a3 : def.pattern = lowercase;
    $ZodCheckStringFormat.init(inst, def);
  });
  const $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => {
    var _a3;
    (_a3 = def.pattern) != null ? _a3 : def.pattern = uppercase;
    $ZodCheckStringFormat.init(inst, def);
  });
  const $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => {
    $ZodCheck.init(inst, def);
    const escapedRegex = escapeRegex(def.includes);
    const pattern2 = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);
    def.pattern = pattern2;
    inst._zod.onattach.push((inst2) => {
      var _a3;
      const bag = inst2._zod.bag;
      (_a3 = bag.patterns) != null ? _a3 : bag.patterns = /* @__PURE__ */ new Set();
      bag.patterns.add(pattern2);
    });
    inst._zod.check = (payload) => {
      if (payload.value.includes(def.includes, def.position))
        return;
      payload.issues.push({
        origin: "string",
        code: "invalid_format",
        format: "includes",
        includes: def.includes,
        input: payload.value,
        inst,
        continue: !def.abort
      });
    };
  });
  const $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => {
    var _a3;
    $ZodCheck.init(inst, def);
    const pattern2 = new RegExp(`^${escapeRegex(def.prefix)}.*`);
    (_a3 = def.pattern) != null ? _a3 : def.pattern = pattern2;
    inst._zod.onattach.push((inst2) => {
      var _a4;
      const bag = inst2._zod.bag;
      (_a4 = bag.patterns) != null ? _a4 : bag.patterns = /* @__PURE__ */ new Set();
      bag.patterns.add(pattern2);
    });
    inst._zod.check = (payload) => {
      if (payload.value.startsWith(def.prefix))
        return;
      payload.issues.push({
        origin: "string",
        code: "invalid_format",
        format: "starts_with",
        prefix: def.prefix,
        input: payload.value,
        inst,
        continue: !def.abort
      });
    };
  });
  const $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => {
    var _a3;
    $ZodCheck.init(inst, def);
    const pattern2 = new RegExp(`.*${escapeRegex(def.suffix)}$`);
    (_a3 = def.pattern) != null ? _a3 : def.pattern = pattern2;
    inst._zod.onattach.push((inst2) => {
      var _a4;
      const bag = inst2._zod.bag;
      (_a4 = bag.patterns) != null ? _a4 : bag.patterns = /* @__PURE__ */ new Set();
      bag.patterns.add(pattern2);
    });
    inst._zod.check = (payload) => {
      if (payload.value.endsWith(def.suffix))
        return;
      payload.issues.push({
        origin: "string",
        code: "invalid_format",
        format: "ends_with",
        suffix: def.suffix,
        input: payload.value,
        inst,
        continue: !def.abort
      });
    };
  });
  function handleCheckPropertyResult(result2, payload, property) {
    if (result2.issues.length) {
      payload.issues.push(...prefixIssues(property, result2.issues));
    }
  }
  const $ZodCheckProperty = /* @__PURE__ */ $constructor("$ZodCheckProperty", (inst, def) => {
    $ZodCheck.init(inst, def);
    inst._zod.check = (payload) => {
      const result2 = def.schema._zod.run({
        value: payload.value[def.property],
        issues: []
      }, {});
      if (result2 instanceof Promise) {
        return result2.then((result3) => handleCheckPropertyResult(result3, payload, def.property));
      }
      handleCheckPropertyResult(result2, payload, def.property);
      return;
    };
  });
  const $ZodCheckMimeType = /* @__PURE__ */ $constructor("$ZodCheckMimeType", (inst, def) => {
    $ZodCheck.init(inst, def);
    const mimeSet = new Set(def.mime);
    inst._zod.onattach.push((inst2) => {
      inst2._zod.bag.mime = def.mime;
    });
    inst._zod.check = (payload) => {
      if (mimeSet.has(payload.value.type))
        return;
      payload.issues.push({
        code: "invalid_value",
        values: def.mime,
        input: payload.value.type,
        inst,
        continue: !def.abort
      });
    };
  });
  const $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => {
    $ZodCheck.init(inst, def);
    inst._zod.check = (payload) => {
      payload.value = def.tx(payload.value);
    };
  });
  class Doc {
    constructor(args = []) {
      this.content = [];
      this.indent = 0;
      if (this)
        this.args = args;
    }
    indented(fn) {
      this.indent += 1;
      fn(this);
      this.indent -= 1;
    }
    write(arg) {
      if (typeof arg === "function") {
        arg(this, { execution: "sync" });
        arg(this, { execution: "async" });
        return;
      }
      const content = arg;
      const lines = content.split("\n").filter((x) => x);
      const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));
      const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x);
      for (const line of dedented) {
        this.content.push(line);
      }
    }
    compile() {
      var _a3;
      const F = Function;
      const args = this == null ? void 0 : this.args;
      const content = (_a3 = this == null ? void 0 : this.content) != null ? _a3 : [``];
      const lines = [...content.map((x) => `  ${x}`)];
      return new F(...args, lines.join("\n"));
    }
  }
  const version = {
    major: 4,
    minor: 2,
    patch: 1
  };
  const $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
    var _a4, _b2, _c2;
    var _a3;
    inst != null ? inst : inst = {};
    inst._zod.def = def;
    inst._zod.bag = inst._zod.bag || {};
    inst._zod.version = version;
    const checks = [...(_a4 = inst._zod.def.checks) != null ? _a4 : []];
    if (inst._zod.traits.has("$ZodCheck")) {
      checks.unshift(inst);
    }
    for (const ch of checks) {
      for (const fn of ch._zod.onattach) {
        fn(inst);
      }
    }
    if (checks.length === 0) {
      (_b2 = (_a3 = inst._zod).deferred) != null ? _b2 : _a3.deferred = [];
      (_c2 = inst._zod.deferred) == null ? void 0 : _c2.push(() => {
        inst._zod.run = inst._zod.parse;
      });
    } else {
      const runChecks = (payload, checks2, ctx) => {
        let isAborted = aborted(payload);
        let asyncResult;
        for (const ch of checks2) {
          if (ch._zod.def.when) {
            const shouldRun = ch._zod.def.when(payload);
            if (!shouldRun)
              continue;
          } else if (isAborted) {
            continue;
          }
          const currLen = payload.issues.length;
          const _ = ch._zod.check(payload);
          if (_ instanceof Promise && (ctx == null ? void 0 : ctx.async) === false) {
            throw new $ZodAsyncError();
          }
          if (asyncResult || _ instanceof Promise) {
            asyncResult = (asyncResult != null ? asyncResult : Promise.resolve()).then(() => __async(null, null, function* () {
              yield _;
              const nextLen = payload.issues.length;
              if (nextLen === currLen)
                return;
              if (!isAborted)
                isAborted = aborted(payload, currLen);
            }));
          } else {
            const nextLen = payload.issues.length;
            if (nextLen === currLen)
              continue;
            if (!isAborted)
              isAborted = aborted(payload, currLen);
          }
        }
        if (asyncResult) {
          return asyncResult.then(() => {
            return payload;
          });
        }
        return payload;
      };
      const handleCanaryResult = (canary, payload, ctx) => {
        if (aborted(canary)) {
          canary.aborted = true;
          return canary;
        }
        const checkResult = runChecks(payload, checks, ctx);
        if (checkResult instanceof Promise) {
          if (ctx.async === false)
            throw new $ZodAsyncError();
          return checkResult.then((checkResult2) => inst._zod.parse(checkResult2, ctx));
        }
        return inst._zod.parse(checkResult, ctx);
      };
      inst._zod.run = (payload, ctx) => {
        if (ctx.skipChecks) {
          return inst._zod.parse(payload, ctx);
        }
        if (ctx.direction === "backward") {
          const canary = inst._zod.parse({ value: payload.value, issues: [] }, __spreadProps(__spreadValues({}, ctx), { skipChecks: true }));
          if (canary instanceof Promise) {
            return canary.then((canary2) => {
              return handleCanaryResult(canary2, payload, ctx);
            });
          }
          return handleCanaryResult(canary, payload, ctx);
        }
        const result2 = inst._zod.parse(payload, ctx);
        if (result2 instanceof Promise) {
          if (ctx.async === false)
            throw new $ZodAsyncError();
          return result2.then((result3) => runChecks(result3, checks, ctx));
        }
        return runChecks(result2, checks, ctx);
      };
    }
    inst["~standard"] = {
      validate: (value) => {
        var _a5;
        try {
          const r = safeParse$2(inst, value);
          return r.success ? { value: r.data } : { issues: (_a5 = r.error) == null ? void 0 : _a5.issues };
        } catch (_) {
          return safeParseAsync$1(inst, value).then((r) => {
            var _a6;
            return r.success ? { value: r.data } : { issues: (_a6 = r.error) == null ? void 0 : _a6.issues };
          });
        }
      },
      vendor: "zod",
      version: 1
    };
  });
  const $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => {
    var _a3, _b2, _c2;
    $ZodType.init(inst, def);
    inst._zod.pattern = (_c2 = [...(_b2 = (_a3 = inst == null ? void 0 : inst._zod.bag) == null ? void 0 : _a3.patterns) != null ? _b2 : []].pop()) != null ? _c2 : string$2(inst._zod.bag);
    inst._zod.parse = (payload, _) => {
      if (def.coerce)
        try {
          payload.value = String(payload.value);
        } catch (_2) {
        }
      if (typeof payload.value === "string")
        return payload;
      payload.issues.push({
        expected: "string",
        code: "invalid_type",
        input: payload.value,
        inst
      });
      return payload;
    };
  });
  const $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def) => {
    $ZodCheckStringFormat.init(inst, def);
    $ZodString.init(inst, def);
  });
  const $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => {
    var _a3;
    (_a3 = def.pattern) != null ? _a3 : def.pattern = guid$1;
    $ZodStringFormat.init(inst, def);
  });
  const $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def) => {
    var _a3, _b2;
    if (def.version) {
      const versionMap = {
        v1: 1,
        v2: 2,
        v3: 3,
        v4: 4,
        v5: 5,
        v6: 6,
        v7: 7,
        v8: 8
      };
      const v = versionMap[def.version];
      if (v === void 0)
        throw new Error(`Invalid UUID version: "${def.version}"`);
      (_a3 = def.pattern) != null ? _a3 : def.pattern = uuid$1(v);
    } else
      (_b2 = def.pattern) != null ? _b2 : def.pattern = uuid$1();
    $ZodStringFormat.init(inst, def);
  });
  const $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => {
    var _a3;
    (_a3 = def.pattern) != null ? _a3 : def.pattern = email$1;
    $ZodStringFormat.init(inst, def);
  });
  const $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => {
    $ZodStringFormat.init(inst, def);
    inst._zod.check = (payload) => {
      try {
        const trimmed = payload.value.trim();
        const url2 = new URL(trimmed);
        if (def.hostname) {
          def.hostname.lastIndex = 0;
          if (!def.hostname.test(url2.hostname)) {
            payload.issues.push({
              code: "invalid_format",
              format: "url",
              note: "Invalid hostname",
              pattern: def.hostname.source,
              input: payload.value,
              inst,
              continue: !def.abort
            });
          }
        }
        if (def.protocol) {
          def.protocol.lastIndex = 0;
          if (!def.protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol)) {
            payload.issues.push({
              code: "invalid_format",
              format: "url",
              note: "Invalid protocol",
              pattern: def.protocol.source,
              input: payload.value,
              inst,
              continue: !def.abort
            });
          }
        }
        if (def.normalize) {
          payload.value = url2.href;
        } else {
          payload.value = trimmed;
        }
        return;
      } catch (_) {
        payload.issues.push({
          code: "invalid_format",
          format: "url",
          input: payload.value,
          inst,
          continue: !def.abort
        });
      }
    };
  });
  const $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => {
    var _a3;
    (_a3 = def.pattern) != null ? _a3 : def.pattern = emoji$1();
    $ZodStringFormat.init(inst, def);
  });
  const $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => {
    var _a3;
    (_a3 = def.pattern) != null ? _a3 : def.pattern = nanoid$2;
    $ZodStringFormat.init(inst, def);
  });
  const $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => {
    var _a3;
    (_a3 = def.pattern) != null ? _a3 : def.pattern = cuid$1;
    $ZodStringFormat.init(inst, def);
  });
  const $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def) => {
    var _a3;
    (_a3 = def.pattern) != null ? _a3 : def.pattern = cuid2$1;
    $ZodStringFormat.init(inst, def);
  });
  const $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def) => {
    var _a3;
    (_a3 = def.pattern) != null ? _a3 : def.pattern = ulid$1;
    $ZodStringFormat.init(inst, def);
  });
  const $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def) => {
    var _a3;
    (_a3 = def.pattern) != null ? _a3 : def.pattern = xid$1;
    $ZodStringFormat.init(inst, def);
  });
  const $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => {
    var _a3;
    (_a3 = def.pattern) != null ? _a3 : def.pattern = ksuid$1;
    $ZodStringFormat.init(inst, def);
  });
  const $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => {
    var _a3;
    (_a3 = def.pattern) != null ? _a3 : def.pattern = datetime$1(def);
    $ZodStringFormat.init(inst, def);
  });
  const $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => {
    var _a3;
    (_a3 = def.pattern) != null ? _a3 : def.pattern = date$3;
    $ZodStringFormat.init(inst, def);
  });
  const $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => {
    var _a3;
    (_a3 = def.pattern) != null ? _a3 : def.pattern = time$1(def);
    $ZodStringFormat.init(inst, def);
  });
  const $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => {
    var _a3;
    (_a3 = def.pattern) != null ? _a3 : def.pattern = duration$1;
    $ZodStringFormat.init(inst, def);
  });
  const $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => {
    var _a3;
    (_a3 = def.pattern) != null ? _a3 : def.pattern = ipv4$1;
    $ZodStringFormat.init(inst, def);
    inst._zod.bag.format = `ipv4`;
  });
  const $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => {
    var _a3;
    (_a3 = def.pattern) != null ? _a3 : def.pattern = ipv6$1;
    $ZodStringFormat.init(inst, def);
    inst._zod.bag.format = `ipv6`;
    inst._zod.check = (payload) => {
      try {
        new URL(`http://[${payload.value}]`);
      } catch (e) {
        payload.issues.push({
          code: "invalid_format",
          format: "ipv6",
          input: payload.value,
          inst,
          continue: !def.abort
        });
      }
    };
  });
  const $ZodMAC = /* @__PURE__ */ $constructor("$ZodMAC", (inst, def) => {
    var _a3;
    (_a3 = def.pattern) != null ? _a3 : def.pattern = mac$1(def.delimiter);
    $ZodStringFormat.init(inst, def);
    inst._zod.bag.format = `mac`;
  });
  const $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => {
    var _a3;
    (_a3 = def.pattern) != null ? _a3 : def.pattern = cidrv4$1;
    $ZodStringFormat.init(inst, def);
  });
  const $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => {
    var _a3;
    (_a3 = def.pattern) != null ? _a3 : def.pattern = cidrv6$1;
    $ZodStringFormat.init(inst, def);
    inst._zod.check = (payload) => {
      const parts = payload.value.split("/");
      try {
        if (parts.length !== 2)
          throw new Error();
        const [address, prefix] = parts;
        if (!prefix)
          throw new Error();
        const prefixNum = Number(prefix);
        if (`${prefixNum}` !== prefix)
          throw new Error();
        if (prefixNum < 0 || prefixNum > 128)
          throw new Error();
        new URL(`http://[${address}]`);
      } catch (e) {
        payload.issues.push({
          code: "invalid_format",
          format: "cidrv6",
          input: payload.value,
          inst,
          continue: !def.abort
        });
      }
    };
  });
  function isValidBase64(data) {
    if (data === "")
      return true;
    if (data.length % 4 !== 0)
      return false;
    try {
      atob(data);
      return true;
    } catch (e) {
      return false;
    }
  }
  const $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => {
    var _a3;
    (_a3 = def.pattern) != null ? _a3 : def.pattern = base64$1;
    $ZodStringFormat.init(inst, def);
    inst._zod.bag.contentEncoding = "base64";
    inst._zod.check = (payload) => {
      if (isValidBase64(payload.value))
        return;
      payload.issues.push({
        code: "invalid_format",
        format: "base64",
        input: payload.value,
        inst,
        continue: !def.abort
      });
    };
  });
  function isValidBase64URL(data) {
    if (!base64url$1.test(data))
      return false;
    const base642 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
    const padded = base642.padEnd(Math.ceil(base642.length / 4) * 4, "=");
    return isValidBase64(padded);
  }
  const $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => {
    var _a3;
    (_a3 = def.pattern) != null ? _a3 : def.pattern = base64url$1;
    $ZodStringFormat.init(inst, def);
    inst._zod.bag.contentEncoding = "base64url";
    inst._zod.check = (payload) => {
      if (isValidBase64URL(payload.value))
        return;
      payload.issues.push({
        code: "invalid_format",
        format: "base64url",
        input: payload.value,
        inst,
        continue: !def.abort
      });
    };
  });
  const $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => {
    var _a3;
    (_a3 = def.pattern) != null ? _a3 : def.pattern = e164$1;
    $ZodStringFormat.init(inst, def);
  });
  function isValidJWT(token, algorithm = null) {
    try {
      const tokensParts = token.split(".");
      if (tokensParts.length !== 3)
        return false;
      const [header] = tokensParts;
      if (!header)
        return false;
      const parsedHeader = JSON.parse(atob(header));
      if ("typ" in parsedHeader && (parsedHeader == null ? void 0 : parsedHeader.typ) !== "JWT")
        return false;
      if (!parsedHeader.alg)
        return false;
      if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm))
        return false;
      return true;
    } catch (e) {
      return false;
    }
  }
  const $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def) => {
    $ZodStringFormat.init(inst, def);
    inst._zod.check = (payload) => {
      if (isValidJWT(payload.value, def.alg))
        return;
      payload.issues.push({
        code: "invalid_format",
        format: "jwt",
        input: payload.value,
        inst,
        continue: !def.abort
      });
    };
  });
  const $ZodCustomStringFormat = /* @__PURE__ */ $constructor("$ZodCustomStringFormat", (inst, def) => {
    $ZodStringFormat.init(inst, def);
    inst._zod.check = (payload) => {
      if (def.fn(payload.value))
        return;
      payload.issues.push({
        code: "invalid_format",
        format: def.format,
        input: payload.value,
        inst,
        continue: !def.abort
      });
    };
  });
  const $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {
    var _a3;
    $ZodType.init(inst, def);
    inst._zod.pattern = (_a3 = inst._zod.bag.pattern) != null ? _a3 : number$2;
    inst._zod.parse = (payload, _ctx) => {
      if (def.coerce)
        try {
          payload.value = Number(payload.value);
        } catch (_) {
        }
      const input = payload.value;
      if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) {
        return payload;
      }
      const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0;
      payload.issues.push(__spreadValues({
        expected: "number",
        code: "invalid_type",
        input,
        inst
      }, received ? { received } : {}));
      return payload;
    };
  });
  const $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumberFormat", (inst, def) => {
    $ZodCheckNumberFormat.init(inst, def);
    $ZodNumber.init(inst, def);
  });
  const $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.pattern = boolean$2;
    inst._zod.parse = (payload, _ctx) => {
      if (def.coerce)
        try {
          payload.value = Boolean(payload.value);
        } catch (_) {
        }
      const input = payload.value;
      if (typeof input === "boolean")
        return payload;
      payload.issues.push({
        expected: "boolean",
        code: "invalid_type",
        input,
        inst
      });
      return payload;
    };
  });
  const $ZodBigInt = /* @__PURE__ */ $constructor("$ZodBigInt", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.pattern = bigint$2;
    inst._zod.parse = (payload, _ctx) => {
      if (def.coerce)
        try {
          payload.value = BigInt(payload.value);
        } catch (_) {
        }
      if (typeof payload.value === "bigint")
        return payload;
      payload.issues.push({
        expected: "bigint",
        code: "invalid_type",
        input: payload.value,
        inst
      });
      return payload;
    };
  });
  const $ZodBigIntFormat = /* @__PURE__ */ $constructor("$ZodBigIntFormat", (inst, def) => {
    $ZodCheckBigIntFormat.init(inst, def);
    $ZodBigInt.init(inst, def);
  });
  const $ZodSymbol = /* @__PURE__ */ $constructor("$ZodSymbol", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.parse = (payload, _ctx) => {
      const input = payload.value;
      if (typeof input === "symbol")
        return payload;
      payload.issues.push({
        expected: "symbol",
        code: "invalid_type",
        input,
        inst
      });
      return payload;
    };
  });
  const $ZodUndefined = /* @__PURE__ */ $constructor("$ZodUndefined", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.pattern = _undefined$2;
    inst._zod.values = /* @__PURE__ */ new Set([void 0]);
    inst._zod.optin = "optional";
    inst._zod.optout = "optional";
    inst._zod.parse = (payload, _ctx) => {
      const input = payload.value;
      if (typeof input === "undefined")
        return payload;
      payload.issues.push({
        expected: "undefined",
        code: "invalid_type",
        input,
        inst
      });
      return payload;
    };
  });
  const $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.pattern = _null$2;
    inst._zod.values = /* @__PURE__ */ new Set([null]);
    inst._zod.parse = (payload, _ctx) => {
      const input = payload.value;
      if (input === null)
        return payload;
      payload.issues.push({
        expected: "null",
        code: "invalid_type",
        input,
        inst
      });
      return payload;
    };
  });
  const $ZodAny = /* @__PURE__ */ $constructor("$ZodAny", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.parse = (payload) => payload;
  });
  const $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.parse = (payload) => payload;
  });
  const $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.parse = (payload, _ctx) => {
      payload.issues.push({
        expected: "never",
        code: "invalid_type",
        input: payload.value,
        inst
      });
      return payload;
    };
  });
  const $ZodVoid = /* @__PURE__ */ $constructor("$ZodVoid", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.parse = (payload, _ctx) => {
      const input = payload.value;
      if (typeof input === "undefined")
        return payload;
      payload.issues.push({
        expected: "void",
        code: "invalid_type",
        input,
        inst
      });
      return payload;
    };
  });
  const $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.parse = (payload, _ctx) => {
      if (def.coerce) {
        try {
          payload.value = new Date(payload.value);
        } catch (_err) {
        }
      }
      const input = payload.value;
      const isDate = input instanceof Date;
      const isValidDate = isDate && !Number.isNaN(input.getTime());
      if (isValidDate)
        return payload;
      payload.issues.push(__spreadProps(__spreadValues({
        expected: "date",
        code: "invalid_type",
        input
      }, isDate ? { received: "Invalid Date" } : {}), {
        inst
      }));
      return payload;
    };
  });
  function handleArrayResult(result2, final, index2) {
    if (result2.issues.length) {
      final.issues.push(...prefixIssues(index2, result2.issues));
    }
    final.value[index2] = result2.value;
  }
  const $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.parse = (payload, ctx) => {
      const input = payload.value;
      if (!Array.isArray(input)) {
        payload.issues.push({
          expected: "array",
          code: "invalid_type",
          input,
          inst
        });
        return payload;
      }
      payload.value = Array(input.length);
      const proms = [];
      for (let i2 = 0; i2 < input.length; i2++) {
        const item = input[i2];
        const result2 = def.element._zod.run({
          value: item,
          issues: []
        }, ctx);
        if (result2 instanceof Promise) {
          proms.push(result2.then((result3) => handleArrayResult(result3, payload, i2)));
        } else {
          handleArrayResult(result2, payload, i2);
        }
      }
      if (proms.length) {
        return Promise.all(proms).then(() => payload);
      }
      return payload;
    };
  });
  function handlePropertyResult(result2, final, key, input) {
    if (result2.issues.length) {
      final.issues.push(...prefixIssues(key, result2.issues));
    }
    if (result2.value === void 0) {
      if (key in input) {
        final.value[key] = void 0;
      }
    } else {
      final.value[key] = result2.value;
    }
  }
  function normalizeDef(def) {
    var _a3, _b2, _c2, _d2;
    const keys = Object.keys(def.shape);
    for (const k of keys) {
      if (!((_d2 = (_c2 = (_b2 = (_a3 = def.shape) == null ? void 0 : _a3[k]) == null ? void 0 : _b2._zod) == null ? void 0 : _c2.traits) == null ? void 0 : _d2.has("$ZodType"))) {
        throw new Error(`Invalid element at key "${k}": expected a Zod schema`);
      }
    }
    const okeys = optionalKeys(def.shape);
    return __spreadProps(__spreadValues({}, def), {
      keys,
      keySet: new Set(keys),
      numKeys: keys.length,
      optionalKeys: new Set(okeys)
    });
  }
  function handleCatchall(proms, input, payload, ctx, def, inst) {
    const unrecognized = [];
    const keySet = def.keySet;
    const _catchall = def.catchall._zod;
    const t = _catchall.def.type;
    for (const key in input) {
      if (keySet.has(key))
        continue;
      if (t === "never") {
        unrecognized.push(key);
        continue;
      }
      const r = _catchall.run({ value: input[key], issues: [] }, ctx);
      if (r instanceof Promise) {
        proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input)));
      } else {
        handlePropertyResult(r, payload, key, input);
      }
    }
    if (unrecognized.length) {
      payload.issues.push({
        code: "unrecognized_keys",
        keys: unrecognized,
        input,
        inst
      });
    }
    if (!proms.length)
      return payload;
    return Promise.all(proms).then(() => {
      return payload;
    });
  }
  const $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
    $ZodType.init(inst, def);
    const desc = Object.getOwnPropertyDescriptor(def, "shape");
    if (!(desc == null ? void 0 : desc.get)) {
      const sh = def.shape;
      Object.defineProperty(def, "shape", {
        get: () => {
          const newSh = __spreadValues({}, sh);
          Object.defineProperty(def, "shape", {
            value: newSh
          });
          return newSh;
        }
      });
    }
    const _normalized = cached(() => normalizeDef(def));
    defineLazy(inst._zod, "propValues", () => {
      var _a3;
      const shape = def.shape;
      const propValues = {};
      for (const key in shape) {
        const field = shape[key]._zod;
        if (field.values) {
          (_a3 = propValues[key]) != null ? _a3 : propValues[key] = /* @__PURE__ */ new Set();
          for (const v of field.values)
            propValues[key].add(v);
        }
      }
      return propValues;
    });
    const isObject$1 = isObject;
    const catchall = def.catchall;
    let value;
    inst._zod.parse = (payload, ctx) => {
      value != null ? value : value = _normalized.value;
      const input = payload.value;
      if (!isObject$1(input)) {
        payload.issues.push({
          expected: "object",
          code: "invalid_type",
          input,
          inst
        });
        return payload;
      }
      payload.value = {};
      const proms = [];
      const shape = value.shape;
      for (const key of value.keys) {
        const el = shape[key];
        const r = el._zod.run({ value: input[key], issues: [] }, ctx);
        if (r instanceof Promise) {
          proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input)));
        } else {
          handlePropertyResult(r, payload, key, input);
        }
      }
      if (!catchall) {
        return proms.length ? Promise.all(proms).then(() => payload) : payload;
      }
      return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);
    };
  });
  const $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => {
    $ZodObject.init(inst, def);
    const superParse = inst._zod.parse;
    const _normalized = cached(() => normalizeDef(def));
    const generateFastpass = (shape) => {
      const doc = new Doc(["shape", "payload", "ctx"]);
      const normalized = _normalized.value;
      const parseStr = (key) => {
        const k = esc(key);
        return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
      };
      doc.write(`const input = payload.value;`);
      const ids = /* @__PURE__ */ Object.create(null);
      let counter = 0;
      for (const key of normalized.keys) {
        ids[key] = `key_${counter++}`;
      }
      doc.write(`const newResult = {};`);
      for (const key of normalized.keys) {
        const id2 = ids[key];
        const k = esc(key);
        doc.write(`const ${id2} = ${parseStr(key)};`);
        doc.write(`
        if (${id2}.issues.length) {
          payload.issues = payload.issues.concat(${id2}.issues.map(iss => ({
            ...iss,
            path: iss.path ? [${k}, ...iss.path] : [${k}]
          })));
        }
        
        
        if (${id2}.value === undefined) {
          if (${k} in input) {
            newResult[${k}] = undefined;
          }
        } else {
          newResult[${k}] = ${id2}.value;
        }
        
      `);
      }
      doc.write(`payload.value = newResult;`);
      doc.write(`return payload;`);
      const fn = doc.compile();
      return (payload, ctx) => fn(shape, payload, ctx);
    };
    let fastpass;
    const isObject$1 = isObject;
    const jit = !globalConfig.jitless;
    const allowsEval$1 = allowsEval;
    const fastEnabled = jit && allowsEval$1.value;
    const catchall = def.catchall;
    let value;
    inst._zod.parse = (payload, ctx) => {
      value != null ? value : value = _normalized.value;
      const input = payload.value;
      if (!isObject$1(input)) {
        payload.issues.push({
          expected: "object",
          code: "invalid_type",
          input,
          inst
        });
        return payload;
      }
      if (jit && fastEnabled && (ctx == null ? void 0 : ctx.async) === false && ctx.jitless !== true) {
        if (!fastpass)
          fastpass = generateFastpass(def.shape);
        payload = fastpass(payload, ctx);
        if (!catchall)
          return payload;
        return handleCatchall([], input, payload, ctx, value, inst);
      }
      return superParse(payload, ctx);
    };
  });
  function handleUnionResults(results, final, inst, ctx) {
    for (const result2 of results) {
      if (result2.issues.length === 0) {
        final.value = result2.value;
        return final;
      }
    }
    const nonaborted = results.filter((r) => !aborted(r));
    if (nonaborted.length === 1) {
      final.value = nonaborted[0].value;
      return nonaborted[0];
    }
    final.issues.push({
      code: "invalid_union",
      input: final.value,
      inst,
      errors: results.map((result2) => result2.issues.map((iss) => finalizeIssue(iss, ctx, config())))
    });
    return final;
  }
  const $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => {
    $ZodType.init(inst, def);
    defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : void 0);
    defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0);
    defineLazy(inst._zod, "values", () => {
      if (def.options.every((o) => o._zod.values)) {
        return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));
      }
      return void 0;
    });
    defineLazy(inst._zod, "pattern", () => {
      if (def.options.every((o) => o._zod.pattern)) {
        const patterns = def.options.map((o) => o._zod.pattern);
        return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`);
      }
      return void 0;
    });
    const single = def.options.length === 1;
    const first = def.options[0]._zod.run;
    inst._zod.parse = (payload, ctx) => {
      if (single) {
        return first(payload, ctx);
      }
      let async = false;
      const results = [];
      for (const option of def.options) {
        const result2 = option._zod.run({
          value: payload.value,
          issues: []
        }, ctx);
        if (result2 instanceof Promise) {
          results.push(result2);
          async = true;
        } else {
          if (result2.issues.length === 0)
            return result2;
          results.push(result2);
        }
      }
      if (!async)
        return handleUnionResults(results, payload, inst, ctx);
      return Promise.all(results).then((results2) => {
        return handleUnionResults(results2, payload, inst, ctx);
      });
    };
  });
  function handleExclusiveUnionResults(results, final, inst, ctx) {
    const successes = results.filter((r) => r.issues.length === 0);
    if (successes.length === 1) {
      final.value = successes[0].value;
      return final;
    }
    if (successes.length === 0) {
      final.issues.push({
        code: "invalid_union",
        input: final.value,
        inst,
        errors: results.map((result2) => result2.issues.map((iss) => finalizeIssue(iss, ctx, config())))
      });
    } else {
      final.issues.push({
        code: "invalid_union",
        input: final.value,
        inst,
        errors: [],
        inclusive: false
      });
    }
    return final;
  }
  const $ZodXor = /* @__PURE__ */ $constructor("$ZodXor", (inst, def) => {
    $ZodUnion.init(inst, def);
    def.inclusive = false;
    const single = def.options.length === 1;
    const first = def.options[0]._zod.run;
    inst._zod.parse = (payload, ctx) => {
      if (single) {
        return first(payload, ctx);
      }
      let async = false;
      const results = [];
      for (const option of def.options) {
        const result2 = option._zod.run({
          value: payload.value,
          issues: []
        }, ctx);
        if (result2 instanceof Promise) {
          results.push(result2);
          async = true;
        } else {
          results.push(result2);
        }
      }
      if (!async)
        return handleExclusiveUnionResults(results, payload, inst, ctx);
      return Promise.all(results).then((results2) => {
        return handleExclusiveUnionResults(results2, payload, inst, ctx);
      });
    };
  });
  const $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => {
    def.inclusive = false;
    $ZodUnion.init(inst, def);
    const _super = inst._zod.parse;
    defineLazy(inst._zod, "propValues", () => {
      const propValues = {};
      for (const option of def.options) {
        const pv = option._zod.propValues;
        if (!pv || Object.keys(pv).length === 0)
          throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);
        for (const [k, v] of Object.entries(pv)) {
          if (!propValues[k])
            propValues[k] = /* @__PURE__ */ new Set();
          for (const val of v) {
            propValues[k].add(val);
          }
        }
      }
      return propValues;
    });
    const disc = cached(() => {
      var _a3;
      const opts = def.options;
      const map2 = /* @__PURE__ */ new Map();
      for (const o of opts) {
        const values = (_a3 = o._zod.propValues) == null ? void 0 : _a3[def.discriminator];
        if (!values || values.size === 0)
          throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`);
        for (const v of values) {
          if (map2.has(v)) {
            throw new Error(`Duplicate discriminator value "${String(v)}"`);
          }
          map2.set(v, o);
        }
      }
      return map2;
    });
    inst._zod.parse = (payload, ctx) => {
      const input = payload.value;
      if (!isObject(input)) {
        payload.issues.push({
          code: "invalid_type",
          expected: "object",
          input,
          inst
        });
        return payload;
      }
      const opt = disc.value.get(input == null ? void 0 : input[def.discriminator]);
      if (opt) {
        return opt._zod.run(payload, ctx);
      }
      if (def.unionFallback) {
        return _super(payload, ctx);
      }
      payload.issues.push({
        code: "invalid_union",
        errors: [],
        note: "No matching discriminator",
        discriminator: def.discriminator,
        input,
        path: [def.discriminator],
        inst
      });
      return payload;
    };
  });
  const $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.parse = (payload, ctx) => {
      const input = payload.value;
      const left = def.left._zod.run({ value: input, issues: [] }, ctx);
      const right = def.right._zod.run({ value: input, issues: [] }, ctx);
      const async = left instanceof Promise || right instanceof Promise;
      if (async) {
        return Promise.all([left, right]).then(([left2, right2]) => {
          return handleIntersectionResults(payload, left2, right2);
        });
      }
      return handleIntersectionResults(payload, left, right);
    };
  });
  function mergeValues(a, b) {
    if (a === b) {
      return { valid: true, data: a };
    }
    if (a instanceof Date && b instanceof Date && +a === +b) {
      return { valid: true, data: a };
    }
    if (isPlainObject$1(a) && isPlainObject$1(b)) {
      const bKeys = Object.keys(b);
      const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
      const newObj = __spreadValues(__spreadValues({}, a), b);
      for (const key of sharedKeys) {
        const sharedValue = mergeValues(a[key], b[key]);
        if (!sharedValue.valid) {
          return {
            valid: false,
            mergeErrorPath: [key, ...sharedValue.mergeErrorPath]
          };
        }
        newObj[key] = sharedValue.data;
      }
      return { valid: true, data: newObj };
    }
    if (Array.isArray(a) && Array.isArray(b)) {
      if (a.length !== b.length) {
        return { valid: false, mergeErrorPath: [] };
      }
      const newArray = [];
      for (let index2 = 0; index2 < a.length; index2++) {
        const itemA = a[index2];
        const itemB = b[index2];
        const sharedValue = mergeValues(itemA, itemB);
        if (!sharedValue.valid) {
          return {
            valid: false,
            mergeErrorPath: [index2, ...sharedValue.mergeErrorPath]
          };
        }
        newArray.push(sharedValue.data);
      }
      return { valid: true, data: newArray };
    }
    return { valid: false, mergeErrorPath: [] };
  }
  function handleIntersectionResults(result2, left, right) {
    if (left.issues.length) {
      result2.issues.push(...left.issues);
    }
    if (right.issues.length) {
      result2.issues.push(...right.issues);
    }
    if (aborted(result2))
      return result2;
    const merged = mergeValues(left.value, right.value);
    if (!merged.valid) {
      throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`);
    }
    result2.value = merged.data;
    return result2;
  }
  const $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => {
    $ZodType.init(inst, def);
    const items2 = def.items;
    inst._zod.parse = (payload, ctx) => {
      const input = payload.value;
      if (!Array.isArray(input)) {
        payload.issues.push({
          input,
          inst,
          expected: "tuple",
          code: "invalid_type"
        });
        return payload;
      }
      payload.value = [];
      const proms = [];
      const reversedIndex = [...items2].reverse().findIndex((item) => item._zod.optin !== "optional");
      const optStart = reversedIndex === -1 ? 0 : items2.length - reversedIndex;
      if (!def.rest) {
        const tooBig = input.length > items2.length;
        const tooSmall = input.length < optStart - 1;
        if (tooBig || tooSmall) {
          payload.issues.push(__spreadProps(__spreadValues({}, tooBig ? { code: "too_big", maximum: items2.length } : { code: "too_small", minimum: items2.length }), {
            input,
            inst,
            origin: "array"
          }));
          return payload;
        }
      }
      let i2 = -1;
      for (const item of items2) {
        i2++;
        if (i2 >= input.length) {
          if (i2 >= optStart)
            continue;
        }
        const result2 = item._zod.run({
          value: input[i2],
          issues: []
        }, ctx);
        if (result2 instanceof Promise) {
          proms.push(result2.then((result3) => handleTupleResult(result3, payload, i2)));
        } else {
          handleTupleResult(result2, payload, i2);
        }
      }
      if (def.rest) {
        const rest = input.slice(items2.length);
        for (const el of rest) {
          i2++;
          const result2 = def.rest._zod.run({
            value: el,
            issues: []
          }, ctx);
          if (result2 instanceof Promise) {
            proms.push(result2.then((result3) => handleTupleResult(result3, payload, i2)));
          } else {
            handleTupleResult(result2, payload, i2);
          }
        }
      }
      if (proms.length)
        return Promise.all(proms).then(() => payload);
      return payload;
    };
  });
  function handleTupleResult(result2, final, index2) {
    if (result2.issues.length) {
      final.issues.push(...prefixIssues(index2, result2.issues));
    }
    final.value[index2] = result2.value;
  }
  const $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.parse = (payload, ctx) => {
      const input = payload.value;
      if (!isPlainObject$1(input)) {
        payload.issues.push({
          expected: "record",
          code: "invalid_type",
          input,
          inst
        });
        return payload;
      }
      const proms = [];
      const values = def.keyType._zod.values;
      if (values) {
        payload.value = {};
        const recordKeys = /* @__PURE__ */ new Set();
        for (const key of values) {
          if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
            recordKeys.add(typeof key === "number" ? key.toString() : key);
            const result2 = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
            if (result2 instanceof Promise) {
              proms.push(result2.then((result3) => {
                if (result3.issues.length) {
                  payload.issues.push(...prefixIssues(key, result3.issues));
                }
                payload.value[key] = result3.value;
              }));
            } else {
              if (result2.issues.length) {
                payload.issues.push(...prefixIssues(key, result2.issues));
              }
              payload.value[key] = result2.value;
            }
          }
        }
        let unrecognized;
        for (const key in input) {
          if (!recordKeys.has(key)) {
            unrecognized = unrecognized != null ? unrecognized : [];
            unrecognized.push(key);
          }
        }
        if (unrecognized && unrecognized.length > 0) {
          payload.issues.push({
            code: "unrecognized_keys",
            input,
            inst,
            keys: unrecognized
          });
        }
      } else {
        payload.value = {};
        for (const key of Reflect.ownKeys(input)) {
          if (key === "__proto__")
            continue;
          const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
          if (keyResult instanceof Promise) {
            throw new Error("Async schemas not supported in object keys currently");
          }
          if (keyResult.issues.length) {
            if (def.mode === "loose") {
              payload.value[key] = input[key];
            } else {
              payload.issues.push({
                code: "invalid_key",
                origin: "record",
                issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
                input: key,
                path: [key],
                inst
              });
            }
            continue;
          }
          const result2 = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
          if (result2 instanceof Promise) {
            proms.push(result2.then((result3) => {
              if (result3.issues.length) {
                payload.issues.push(...prefixIssues(key, result3.issues));
              }
              payload.value[keyResult.value] = result3.value;
            }));
          } else {
            if (result2.issues.length) {
              payload.issues.push(...prefixIssues(key, result2.issues));
            }
            payload.value[keyResult.value] = result2.value;
          }
        }
      }
      if (proms.length) {
        return Promise.all(proms).then(() => payload);
      }
      return payload;
    };
  });
  const $ZodMap = /* @__PURE__ */ $constructor("$ZodMap", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.parse = (payload, ctx) => {
      const input = payload.value;
      if (!(input instanceof Map)) {
        payload.issues.push({
          expected: "map",
          code: "invalid_type",
          input,
          inst
        });
        return payload;
      }
      const proms = [];
      payload.value = /* @__PURE__ */ new Map();
      for (const [key, value] of input) {
        const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
        const valueResult = def.valueType._zod.run({ value, issues: [] }, ctx);
        if (keyResult instanceof Promise || valueResult instanceof Promise) {
          proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => {
            handleMapResult(keyResult2, valueResult2, payload, key, input, inst, ctx);
          }));
        } else {
          handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);
        }
      }
      if (proms.length)
        return Promise.all(proms).then(() => payload);
      return payload;
    };
  });
  function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {
    if (keyResult.issues.length) {
      if (propertyKeyTypes.has(typeof key)) {
        final.issues.push(...prefixIssues(key, keyResult.issues));
      } else {
        final.issues.push({
          code: "invalid_key",
          origin: "map",
          input,
          inst,
          issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config()))
        });
      }
    }
    if (valueResult.issues.length) {
      if (propertyKeyTypes.has(typeof key)) {
        final.issues.push(...prefixIssues(key, valueResult.issues));
      } else {
        final.issues.push({
          origin: "map",
          code: "invalid_element",
          input,
          inst,
          key,
          issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config()))
        });
      }
    }
    final.value.set(keyResult.value, valueResult.value);
  }
  const $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.parse = (payload, ctx) => {
      const input = payload.value;
      if (!(input instanceof Set)) {
        payload.issues.push({
          input,
          inst,
          expected: "set",
          code: "invalid_type"
        });
        return payload;
      }
      const proms = [];
      payload.value = /* @__PURE__ */ new Set();
      for (const item of input) {
        const result2 = def.valueType._zod.run({ value: item, issues: [] }, ctx);
        if (result2 instanceof Promise) {
          proms.push(result2.then((result3) => handleSetResult(result3, payload)));
        } else
          handleSetResult(result2, payload);
      }
      if (proms.length)
        return Promise.all(proms).then(() => payload);
      return payload;
    };
  });
  function handleSetResult(result2, final) {
    if (result2.issues.length) {
      final.issues.push(...result2.issues);
    }
    final.value.add(result2.value);
  }
  const $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
    $ZodType.init(inst, def);
    const values = getEnumValues(def.entries);
    const valuesSet = new Set(values);
    inst._zod.values = valuesSet;
    inst._zod.pattern = new RegExp(`^(${values.filter((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.toString()).join("|")})$`);
    inst._zod.parse = (payload, _ctx) => {
      const input = payload.value;
      if (valuesSet.has(input)) {
        return payload;
      }
      payload.issues.push({
        code: "invalid_value",
        values,
        input,
        inst
      });
      return payload;
    };
  });
  const $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => {
    $ZodType.init(inst, def);
    if (def.values.length === 0) {
      throw new Error("Cannot create literal schema with no valid values");
    }
    const values = new Set(def.values);
    inst._zod.values = values;
    inst._zod.pattern = new RegExp(`^(${def.values.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$`);
    inst._zod.parse = (payload, _ctx) => {
      const input = payload.value;
      if (values.has(input)) {
        return payload;
      }
      payload.issues.push({
        code: "invalid_value",
        values: def.values,
        input,
        inst
      });
      return payload;
    };
  });
  const $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.parse = (payload, _ctx) => {
      const input = payload.value;
      if (input instanceof File)
        return payload;
      payload.issues.push({
        expected: "file",
        code: "invalid_type",
        input,
        inst
      });
      return payload;
    };
  });
  const $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.parse = (payload, ctx) => {
      if (ctx.direction === "backward") {
        throw new $ZodEncodeError(inst.constructor.name);
      }
      const _out = def.transform(payload.value, payload);
      if (ctx.async) {
        const output = _out instanceof Promise ? _out : Promise.resolve(_out);
        return output.then((output2) => {
          payload.value = output2;
          return payload;
        });
      }
      if (_out instanceof Promise) {
        throw new $ZodAsyncError();
      }
      payload.value = _out;
      return payload;
    };
  });
  function handleOptionalResult(result2, input) {
    if (result2.issues.length && input === void 0) {
      return { issues: [], value: void 0 };
    }
    return result2;
  }
  const $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.optin = "optional";
    inst._zod.optout = "optional";
    defineLazy(inst._zod, "values", () => {
      return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0;
    });
    defineLazy(inst._zod, "pattern", () => {
      const pattern2 = def.innerType._zod.pattern;
      return pattern2 ? new RegExp(`^(${cleanRegex(pattern2.source)})?$`) : void 0;
    });
    inst._zod.parse = (payload, ctx) => {
      if (def.innerType._zod.optin === "optional") {
        const result2 = def.innerType._zod.run(payload, ctx);
        if (result2 instanceof Promise)
          return result2.then((r) => handleOptionalResult(r, payload.value));
        return handleOptionalResult(result2, payload.value);
      }
      if (payload.value === void 0) {
        return payload;
      }
      return def.innerType._zod.run(payload, ctx);
    };
  });
  const $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => {
    $ZodType.init(inst, def);
    defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
    defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
    defineLazy(inst._zod, "pattern", () => {
      const pattern2 = def.innerType._zod.pattern;
      return pattern2 ? new RegExp(`^(${cleanRegex(pattern2.source)}|null)$`) : void 0;
    });
    defineLazy(inst._zod, "values", () => {
      return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0;
    });
    inst._zod.parse = (payload, ctx) => {
      if (payload.value === null)
        return payload;
      return def.innerType._zod.run(payload, ctx);
    };
  });
  const $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.optin = "optional";
    defineLazy(inst._zod, "values", () => def.innerType._zod.values);
    inst._zod.parse = (payload, ctx) => {
      if (ctx.direction === "backward") {
        return def.innerType._zod.run(payload, ctx);
      }
      if (payload.value === void 0) {
        payload.value = def.defaultValue;
        return payload;
      }
      const result2 = def.innerType._zod.run(payload, ctx);
      if (result2 instanceof Promise) {
        return result2.then((result3) => handleDefaultResult(result3, def));
      }
      return handleDefaultResult(result2, def);
    };
  });
  function handleDefaultResult(payload, def) {
    if (payload.value === void 0) {
      payload.value = def.defaultValue;
    }
    return payload;
  }
  const $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.optin = "optional";
    defineLazy(inst._zod, "values", () => def.innerType._zod.values);
    inst._zod.parse = (payload, ctx) => {
      if (ctx.direction === "backward") {
        return def.innerType._zod.run(payload, ctx);
      }
      if (payload.value === void 0) {
        payload.value = def.defaultValue;
      }
      return def.innerType._zod.run(payload, ctx);
    };
  });
  const $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => {
    $ZodType.init(inst, def);
    defineLazy(inst._zod, "values", () => {
      const v = def.innerType._zod.values;
      return v ? new Set([...v].filter((x) => x !== void 0)) : void 0;
    });
    inst._zod.parse = (payload, ctx) => {
      const result2 = def.innerType._zod.run(payload, ctx);
      if (result2 instanceof Promise) {
        return result2.then((result3) => handleNonOptionalResult(result3, inst));
      }
      return handleNonOptionalResult(result2, inst);
    };
  });
  function handleNonOptionalResult(payload, inst) {
    if (!payload.issues.length && payload.value === void 0) {
      payload.issues.push({
        code: "invalid_type",
        expected: "nonoptional",
        input: payload.value,
        inst
      });
    }
    return payload;
  }
  const $ZodSuccess = /* @__PURE__ */ $constructor("$ZodSuccess", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.parse = (payload, ctx) => {
      if (ctx.direction === "backward") {
        throw new $ZodEncodeError("ZodSuccess");
      }
      const result2 = def.innerType._zod.run(payload, ctx);
      if (result2 instanceof Promise) {
        return result2.then((result3) => {
          payload.value = result3.issues.length === 0;
          return payload;
        });
      }
      payload.value = result2.issues.length === 0;
      return payload;
    };
  });
  const $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => {
    $ZodType.init(inst, def);
    defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
    defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
    defineLazy(inst._zod, "values", () => def.innerType._zod.values);
    inst._zod.parse = (payload, ctx) => {
      if (ctx.direction === "backward") {
        return def.innerType._zod.run(payload, ctx);
      }
      const result2 = def.innerType._zod.run(payload, ctx);
      if (result2 instanceof Promise) {
        return result2.then((result3) => {
          payload.value = result3.value;
          if (result3.issues.length) {
            payload.value = def.catchValue(__spreadProps(__spreadValues({}, payload), {
              error: {
                issues: result3.issues.map((iss) => finalizeIssue(iss, ctx, config()))
              },
              input: payload.value
            }));
            payload.issues = [];
          }
          return payload;
        });
      }
      payload.value = result2.value;
      if (result2.issues.length) {
        payload.value = def.catchValue(__spreadProps(__spreadValues({}, payload), {
          error: {
            issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config()))
          },
          input: payload.value
        }));
        payload.issues = [];
      }
      return payload;
    };
  });
  const $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.parse = (payload, _ctx) => {
      if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) {
        payload.issues.push({
          input: payload.value,
          inst,
          expected: "nan",
          code: "invalid_type"
        });
        return payload;
      }
      return payload;
    };
  });
  const $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => {
    $ZodType.init(inst, def);
    defineLazy(inst._zod, "values", () => def.in._zod.values);
    defineLazy(inst._zod, "optin", () => def.in._zod.optin);
    defineLazy(inst._zod, "optout", () => def.out._zod.optout);
    defineLazy(inst._zod, "propValues", () => def.in._zod.propValues);
    inst._zod.parse = (payload, ctx) => {
      if (ctx.direction === "backward") {
        const right = def.out._zod.run(payload, ctx);
        if (right instanceof Promise) {
          return right.then((right2) => handlePipeResult(right2, def.in, ctx));
        }
        return handlePipeResult(right, def.in, ctx);
      }
      const left = def.in._zod.run(payload, ctx);
      if (left instanceof Promise) {
        return left.then((left2) => handlePipeResult(left2, def.out, ctx));
      }
      return handlePipeResult(left, def.out, ctx);
    };
  });
  function handlePipeResult(left, next, ctx) {
    if (left.issues.length) {
      left.aborted = true;
      return left;
    }
    return next._zod.run({ value: left.value, issues: left.issues }, ctx);
  }
  const $ZodCodec = /* @__PURE__ */ $constructor("$ZodCodec", (inst, def) => {
    $ZodType.init(inst, def);
    defineLazy(inst._zod, "values", () => def.in._zod.values);
    defineLazy(inst._zod, "optin", () => def.in._zod.optin);
    defineLazy(inst._zod, "optout", () => def.out._zod.optout);
    defineLazy(inst._zod, "propValues", () => def.in._zod.propValues);
    inst._zod.parse = (payload, ctx) => {
      const direction = ctx.direction || "forward";
      if (direction === "forward") {
        const left = def.in._zod.run(payload, ctx);
        if (left instanceof Promise) {
          return left.then((left2) => handleCodecAResult(left2, def, ctx));
        }
        return handleCodecAResult(left, def, ctx);
      } else {
        const right = def.out._zod.run(payload, ctx);
        if (right instanceof Promise) {
          return right.then((right2) => handleCodecAResult(right2, def, ctx));
        }
        return handleCodecAResult(right, def, ctx);
      }
    };
  });
  function handleCodecAResult(result2, def, ctx) {
    if (result2.issues.length) {
      result2.aborted = true;
      return result2;
    }
    const direction = ctx.direction || "forward";
    if (direction === "forward") {
      const transformed = def.transform(result2.value, result2);
      if (transformed instanceof Promise) {
        return transformed.then((value) => handleCodecTxResult(result2, value, def.out, ctx));
      }
      return handleCodecTxResult(result2, transformed, def.out, ctx);
    } else {
      const transformed = def.reverseTransform(result2.value, result2);
      if (transformed instanceof Promise) {
        return transformed.then((value) => handleCodecTxResult(result2, value, def.in, ctx));
      }
      return handleCodecTxResult(result2, transformed, def.in, ctx);
    }
  }
  function handleCodecTxResult(left, value, nextSchema, ctx) {
    if (left.issues.length) {
      left.aborted = true;
      return left;
    }
    return nextSchema._zod.run({ value, issues: left.issues }, ctx);
  }
  const $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => {
    $ZodType.init(inst, def);
    defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues);
    defineLazy(inst._zod, "values", () => def.innerType._zod.values);
    defineLazy(inst._zod, "optin", () => {
      var _a3, _b2;
      return (_b2 = (_a3 = def.innerType) == null ? void 0 : _a3._zod) == null ? void 0 : _b2.optin;
    });
    defineLazy(inst._zod, "optout", () => {
      var _a3, _b2;
      return (_b2 = (_a3 = def.innerType) == null ? void 0 : _a3._zod) == null ? void 0 : _b2.optout;
    });
    inst._zod.parse = (payload, ctx) => {
      if (ctx.direction === "backward") {
        return def.innerType._zod.run(payload, ctx);
      }
      const result2 = def.innerType._zod.run(payload, ctx);
      if (result2 instanceof Promise) {
        return result2.then(handleReadonlyResult);
      }
      return handleReadonlyResult(result2);
    };
  });
  function handleReadonlyResult(payload) {
    payload.value = Object.freeze(payload.value);
    return payload;
  }
  const $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (inst, def) => {
    $ZodType.init(inst, def);
    const regexParts = [];
    for (const part of def.parts) {
      if (typeof part === "object" && part !== null) {
        if (!part._zod.pattern) {
          throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);
        }
        const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern;
        if (!source)
          throw new Error(`Invalid template literal part: ${part._zod.traits}`);
        const start = source.startsWith("^") ? 1 : 0;
        const end = source.endsWith("$") ? source.length - 1 : source.length;
        regexParts.push(source.slice(start, end));
      } else if (part === null || primitiveTypes.has(typeof part)) {
        regexParts.push(escapeRegex(`${part}`));
      } else {
        throw new Error(`Invalid template literal part: ${part}`);
      }
    }
    inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`);
    inst._zod.parse = (payload, _ctx) => {
      var _a3;
      if (typeof payload.value !== "string") {
        payload.issues.push({
          input: payload.value,
          inst,
          expected: "template_literal",
          code: "invalid_type"
        });
        return payload;
      }
      inst._zod.pattern.lastIndex = 0;
      if (!inst._zod.pattern.test(payload.value)) {
        payload.issues.push({
          input: payload.value,
          inst,
          code: "invalid_format",
          format: (_a3 = def.format) != null ? _a3 : "template_literal",
          pattern: inst._zod.pattern.source
        });
        return payload;
      }
      return payload;
    };
  });
  const $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => {
    $ZodType.init(inst, def);
    inst._def = def;
    inst._zod.def = def;
    inst.implement = (func) => {
      if (typeof func !== "function") {
        throw new Error("implement() must be called with a function");
      }
      return function(...args) {
        const parsedArgs = inst._def.input ? parse$1(inst._def.input, args) : args;
        const result2 = Reflect.apply(func, this, parsedArgs);
        if (inst._def.output) {
          return parse$1(inst._def.output, result2);
        }
        return result2;
      };
    };
    inst.implementAsync = (func) => {
      if (typeof func !== "function") {
        throw new Error("implementAsync() must be called with a function");
      }
      return function(...args) {
        return __async(this, null, function* () {
          const parsedArgs = inst._def.input ? yield parseAsync$1(inst._def.input, args) : args;
          const result2 = yield Reflect.apply(func, this, parsedArgs);
          if (inst._def.output) {
            return yield parseAsync$1(inst._def.output, result2);
          }
          return result2;
        });
      };
    };
    inst._zod.parse = (payload, _ctx) => {
      if (typeof payload.value !== "function") {
        payload.issues.push({
          code: "invalid_type",
          expected: "function",
          input: payload.value,
          inst
        });
        return payload;
      }
      const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === "promise";
      if (hasPromiseOutput) {
        payload.value = inst.implementAsync(payload.value);
      } else {
        payload.value = inst.implement(payload.value);
      }
      return payload;
    };
    inst.input = (...args) => {
      const F = inst.constructor;
      if (Array.isArray(args[0])) {
        return new F({
          type: "function",
          input: new $ZodTuple({
            type: "tuple",
            items: args[0],
            rest: args[1]
          }),
          output: inst._def.output
        });
      }
      return new F({
        type: "function",
        input: args[0],
        output: inst._def.output
      });
    };
    inst.output = (output) => {
      const F = inst.constructor;
      return new F({
        type: "function",
        input: inst._def.input,
        output
      });
    };
    return inst;
  });
  const $ZodPromise = /* @__PURE__ */ $constructor("$ZodPromise", (inst, def) => {
    $ZodType.init(inst, def);
    inst._zod.parse = (payload, ctx) => {
      return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));
    };
  });
  const $ZodLazy = /* @__PURE__ */ $constructor("$ZodLazy", (inst, def) => {
    $ZodType.init(inst, def);
    defineLazy(inst._zod, "innerType", () => def.getter());
    defineLazy(inst._zod, "pattern", () => {
      var _a3, _b2;
      return (_b2 = (_a3 = inst._zod.innerType) == null ? void 0 : _a3._zod) == null ? void 0 : _b2.pattern;
    });
    defineLazy(inst._zod, "propValues", () => {
      var _a3, _b2;
      return (_b2 = (_a3 = inst._zod.innerType) == null ? void 0 : _a3._zod) == null ? void 0 : _b2.propValues;
    });
    defineLazy(inst._zod, "optin", () => {
      var _a3, _b2, _c2;
      return (_c2 = (_b2 = (_a3 = inst._zod.innerType) == null ? void 0 : _a3._zod) == null ? void 0 : _b2.optin) != null ? _c2 : void 0;
    });
    defineLazy(inst._zod, "optout", () => {
      var _a3, _b2, _c2;
      return (_c2 = (_b2 = (_a3 = inst._zod.innerType) == null ? void 0 : _a3._zod) == null ? void 0 : _b2.optout) != null ? _c2 : void 0;
    });
    inst._zod.parse = (payload, ctx) => {
      const inner = inst._zod.innerType;
      return inner._zod.run(payload, ctx);
    };
  });
  const $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => {
    $ZodCheck.init(inst, def);
    $ZodType.init(inst, def);
    inst._zod.parse = (payload, _) => {
      return payload;
    };
    inst._zod.check = (payload) => {
      const input = payload.value;
      const r = def.fn(input);
      if (r instanceof Promise) {
        return r.then((r2) => handleRefineResult(r2, payload, input, inst));
      }
      handleRefineResult(r, payload, input, inst);
      return;
    };
  });
  function handleRefineResult(result2, payload, input, inst) {
    var _a3;
    if (!result2) {
      const _iss = {
        code: "custom",
        input,
        inst,
        // incorporates params.error into issue reporting
        path: [...(_a3 = inst._zod.def.path) != null ? _a3 : []],
        // incorporates params.error into issue reporting
        continue: !inst._zod.def.abort
        // params: inst._zod.def.params,
      };
      if (inst._zod.def.params)
        _iss.params = inst._zod.def.params;
      payload.issues.push(issue(_iss));
    }
  }
  const error$I = () => {
    const Sizable = {
      string: { unit: "حرف", verb: "أن يحوي" },
      file: { unit: "بايت", verb: "أن يحوي" },
      array: { unit: "عنصر", verb: "أن يحوي" },
      set: { unit: "عنصر", verb: "أن يحوي" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "number";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "array";
          }
          if (data === null) {
            return "null";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    const Nouns = {
      regex: "مدخل",
      email: "بريد إلكتروني",
      url: "رابط",
      emoji: "إيموجي",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "تاريخ ووقت بمعيار ISO",
      date: "تاريخ بمعيار ISO",
      time: "وقت بمعيار ISO",
      duration: "مدة بمعيار ISO",
      ipv4: "عنوان IPv4",
      ipv6: "عنوان IPv6",
      cidrv4: "مدى عناوين بصيغة IPv4",
      cidrv6: "مدى عناوين بصيغة IPv6",
      base64: "نَص بترميز base64-encoded",
      base64url: "نَص بترميز base64url-encoded",
      json_string: "نَص على هيئة JSON",
      e164: "رقم هاتف بمعيار E.164",
      jwt: "JWT",
      template_literal: "مدخل"
    };
    return (issue2) => {
      var _a3, _b2, _c2, _d2;
      switch (issue2.code) {
        case "invalid_type":
          return `مدخلات غير مقبولة: يفترض إدخال ${issue2.expected}، ولكن تم إدخال ${parsedType2(issue2.input)}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `مدخلات غير مقبولة: يفترض إدخال ${stringifyPrimitive(issue2.values[0])}`;
          return `اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${joinValues(issue2.values, "|")}`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          if (sizing)
            return ` أكبر من اللازم: يفترض أن تكون ${(_a3 = issue2.origin) != null ? _a3 : "القيمة"} ${adj} ${issue2.maximum.toString()} ${(_b2 = sizing.unit) != null ? _b2 : "عنصر"}`;
          return `أكبر من اللازم: يفترض أن تكون ${(_c2 = issue2.origin) != null ? _c2 : "القيمة"} ${adj} ${issue2.maximum.toString()}`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `أصغر من اللازم: يفترض لـ ${issue2.origin} أن يكون ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
          }
          return `أصغر من اللازم: يفترض لـ ${issue2.origin} أن يكون ${adj} ${issue2.minimum.toString()}`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with")
            return `نَص غير مقبول: يجب أن يبدأ بـ "${issue2.prefix}"`;
          if (_issue.format === "ends_with")
            return `نَص غير مقبول: يجب أن ينتهي بـ "${_issue.suffix}"`;
          if (_issue.format === "includes")
            return `نَص غير مقبول: يجب أن يتضمَّن "${_issue.includes}"`;
          if (_issue.format === "regex")
            return `نَص غير مقبول: يجب أن يطابق النمط ${_issue.pattern}`;
          return `${(_d2 = Nouns[_issue.format]) != null ? _d2 : issue2.format} غير مقبول`;
        }
        case "not_multiple_of":
          return `رقم غير مقبول: يجب أن يكون من مضاعفات ${issue2.divisor}`;
        case "unrecognized_keys":
          return `معرف${issue2.keys.length > 1 ? "ات" : ""} غريب${issue2.keys.length > 1 ? "ة" : ""}: ${joinValues(issue2.keys, "، ")}`;
        case "invalid_key":
          return `معرف غير مقبول في ${issue2.origin}`;
        case "invalid_union":
          return "مدخل غير مقبول";
        case "invalid_element":
          return `مدخل غير مقبول في ${issue2.origin}`;
        default:
          return "مدخل غير مقبول";
      }
    };
  };
  function ar() {
    return {
      localeError: error$I()
    };
  }
  const error$H = () => {
    const Sizable = {
      string: { unit: "simvol", verb: "olmalıdır" },
      file: { unit: "bayt", verb: "olmalıdır" },
      array: { unit: "element", verb: "olmalıdır" },
      set: { unit: "element", verb: "olmalıdır" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "number";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "array";
          }
          if (data === null) {
            return "null";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    const Nouns = {
      regex: "input",
      email: "email address",
      url: "URL",
      emoji: "emoji",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "ISO datetime",
      date: "ISO date",
      time: "ISO time",
      duration: "ISO duration",
      ipv4: "IPv4 address",
      ipv6: "IPv6 address",
      cidrv4: "IPv4 range",
      cidrv6: "IPv6 range",
      base64: "base64-encoded string",
      base64url: "base64url-encoded string",
      json_string: "JSON string",
      e164: "E.164 number",
      jwt: "JWT",
      template_literal: "input"
    };
    return (issue2) => {
      var _a3, _b2, _c2, _d2;
      switch (issue2.code) {
        case "invalid_type":
          return `Yanlış dəyər: gözlənilən ${issue2.expected}, daxil olan ${parsedType2(issue2.input)}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `Yanlış dəyər: gözlənilən ${stringifyPrimitive(issue2.values[0])}`;
          return `Yanlış seçim: aşağıdakılardan biri olmalıdır: ${joinValues(issue2.values, "|")}`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          if (sizing)
            return `Çox böyük: gözlənilən ${(_a3 = issue2.origin) != null ? _a3 : "dəyər"} ${adj}${issue2.maximum.toString()} ${(_b2 = sizing.unit) != null ? _b2 : "element"}`;
          return `Çox böyük: gözlənilən ${(_c2 = issue2.origin) != null ? _c2 : "dəyər"} ${adj}${issue2.maximum.toString()}`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          if (sizing)
            return `Çox kiçik: gözlənilən ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
          return `Çox kiçik: gözlənilən ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with")
            return `Yanlış mətn: "${_issue.prefix}" ilə başlamalıdır`;
          if (_issue.format === "ends_with")
            return `Yanlış mətn: "${_issue.suffix}" ilə bitməlidir`;
          if (_issue.format === "includes")
            return `Yanlış mətn: "${_issue.includes}" daxil olmalıdır`;
          if (_issue.format === "regex")
            return `Yanlış mətn: ${_issue.pattern} şablonuna uyğun olmalıdır`;
          return `Yanlış ${(_d2 = Nouns[_issue.format]) != null ? _d2 : issue2.format}`;
        }
        case "not_multiple_of":
          return `Yanlış ədəd: ${issue2.divisor} ilə bölünə bilən olmalıdır`;
        case "unrecognized_keys":
          return `Tanınmayan açar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `${issue2.origin} daxilində yanlış açar`;
        case "invalid_union":
          return "Yanlış dəyər";
        case "invalid_element":
          return `${issue2.origin} daxilində yanlış dəyər`;
        default:
          return `Yanlış dəyər`;
      }
    };
  };
  function az() {
    return {
      localeError: error$H()
    };
  }
  function getBelarusianPlural(count, one, few, many) {
    const absCount = Math.abs(count);
    const lastDigit = absCount % 10;
    const lastTwoDigits = absCount % 100;
    if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
      return many;
    }
    if (lastDigit === 1) {
      return one;
    }
    if (lastDigit >= 2 && lastDigit <= 4) {
      return few;
    }
    return many;
  }
  const error$G = () => {
    const Sizable = {
      string: {
        unit: {
          one: "сімвал",
          few: "сімвалы",
          many: "сімвалаў"
        },
        verb: "мець"
      },
      array: {
        unit: {
          one: "элемент",
          few: "элементы",
          many: "элементаў"
        },
        verb: "мець"
      },
      set: {
        unit: {
          one: "элемент",
          few: "элементы",
          many: "элементаў"
        },
        verb: "мець"
      },
      file: {
        unit: {
          one: "байт",
          few: "байты",
          many: "байтаў"
        },
        verb: "мець"
      }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "лік";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "масіў";
          }
          if (data === null) {
            return "null";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    const Nouns = {
      regex: "увод",
      email: "email адрас",
      url: "URL",
      emoji: "эмодзі",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "ISO дата і час",
      date: "ISO дата",
      time: "ISO час",
      duration: "ISO працягласць",
      ipv4: "IPv4 адрас",
      ipv6: "IPv6 адрас",
      cidrv4: "IPv4 дыяпазон",
      cidrv6: "IPv6 дыяпазон",
      base64: "радок у фармаце base64",
      base64url: "радок у фармаце base64url",
      json_string: "JSON радок",
      e164: "нумар E.164",
      jwt: "JWT",
      template_literal: "увод"
    };
    return (issue2) => {
      var _a3, _b2, _c2;
      switch (issue2.code) {
        case "invalid_type":
          return `Няправільны ўвод: чакаўся ${issue2.expected}, атрымана ${parsedType2(issue2.input)}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `Няправільны ўвод: чакалася ${stringifyPrimitive(issue2.values[0])}`;
          return `Няправільны варыянт: чакаўся адзін з ${joinValues(issue2.values, "|")}`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            const maxValue = Number(issue2.maximum);
            const unit = getBelarusianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
            return `Занадта вялікі: чакалася, што ${(_a3 = issue2.origin) != null ? _a3 : "значэнне"} павінна ${sizing.verb} ${adj}${issue2.maximum.toString()} ${unit}`;
          }
          return `Занадта вялікі: чакалася, што ${(_b2 = issue2.origin) != null ? _b2 : "значэнне"} павінна быць ${adj}${issue2.maximum.toString()}`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            const minValue = Number(issue2.minimum);
            const unit = getBelarusianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
            return `Занадта малы: чакалася, што ${issue2.origin} павінна ${sizing.verb} ${adj}${issue2.minimum.toString()} ${unit}`;
          }
          return `Занадта малы: чакалася, што ${issue2.origin} павінна быць ${adj}${issue2.minimum.toString()}`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with")
            return `Няправільны радок: павінен пачынацца з "${_issue.prefix}"`;
          if (_issue.format === "ends_with")
            return `Няправільны радок: павінен заканчвацца на "${_issue.suffix}"`;
          if (_issue.format === "includes")
            return `Няправільны радок: павінен змяшчаць "${_issue.includes}"`;
          if (_issue.format === "regex")
            return `Няправільны радок: павінен адпавядаць шаблону ${_issue.pattern}`;
          return `Няправільны ${(_c2 = Nouns[_issue.format]) != null ? _c2 : issue2.format}`;
        }
        case "not_multiple_of":
          return `Няправільны лік: павінен быць кратным ${issue2.divisor}`;
        case "unrecognized_keys":
          return `Нераспазнаны ${issue2.keys.length > 1 ? "ключы" : "ключ"}: ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `Няправільны ключ у ${issue2.origin}`;
        case "invalid_union":
          return "Няправільны ўвод";
        case "invalid_element":
          return `Няправільнае значэнне ў ${issue2.origin}`;
        default:
          return `Няправільны ўвод`;
      }
    };
  };
  function be() {
    return {
      localeError: error$G()
    };
  }
  const parsedType$6 = (data) => {
    const t = typeof data;
    switch (t) {
      case "number": {
        return Number.isNaN(data) ? "NaN" : "число";
      }
      case "object": {
        if (Array.isArray(data)) {
          return "масив";
        }
        if (data === null) {
          return "null";
        }
        if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
          return data.constructor.name;
        }
      }
    }
    return t;
  };
  const error$F = () => {
    const Sizable = {
      string: { unit: "символа", verb: "да съдържа" },
      file: { unit: "байта", verb: "да съдържа" },
      array: { unit: "елемента", verb: "да съдържа" },
      set: { unit: "елемента", verb: "да съдържа" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const Nouns = {
      regex: "вход",
      email: "имейл адрес",
      url: "URL",
      emoji: "емоджи",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "ISO време",
      date: "ISO дата",
      time: "ISO време",
      duration: "ISO продължителност",
      ipv4: "IPv4 адрес",
      ipv6: "IPv6 адрес",
      cidrv4: "IPv4 диапазон",
      cidrv6: "IPv6 диапазон",
      base64: "base64-кодиран низ",
      base64url: "base64url-кодиран низ",
      json_string: "JSON низ",
      e164: "E.164 номер",
      jwt: "JWT",
      template_literal: "вход"
    };
    return (issue2) => {
      var _a3, _b2, _c2, _d2;
      switch (issue2.code) {
        case "invalid_type":
          return `Невалиден вход: очакван ${issue2.expected}, получен ${parsedType$6(issue2.input)}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `Невалиден вход: очакван ${stringifyPrimitive(issue2.values[0])}`;
          return `Невалидна опция: очаквано едно от ${joinValues(issue2.values, "|")}`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          if (sizing)
            return `Твърде голямо: очаква се ${(_a3 = issue2.origin) != null ? _a3 : "стойност"} да съдържа ${adj}${issue2.maximum.toString()} ${(_b2 = sizing.unit) != null ? _b2 : "елемента"}`;
          return `Твърде голямо: очаква се ${(_c2 = issue2.origin) != null ? _c2 : "стойност"} да бъде ${adj}${issue2.maximum.toString()}`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `Твърде малко: очаква се ${issue2.origin} да съдържа ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
          }
          return `Твърде малко: очаква се ${issue2.origin} да бъде ${adj}${issue2.minimum.toString()}`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with") {
            return `Невалиден низ: трябва да започва с "${_issue.prefix}"`;
          }
          if (_issue.format === "ends_with")
            return `Невалиден низ: трябва да завършва с "${_issue.suffix}"`;
          if (_issue.format === "includes")
            return `Невалиден низ: трябва да включва "${_issue.includes}"`;
          if (_issue.format === "regex")
            return `Невалиден низ: трябва да съвпада с ${_issue.pattern}`;
          let invalid_adj = "Невалиден";
          if (_issue.format === "emoji")
            invalid_adj = "Невалидно";
          if (_issue.format === "datetime")
            invalid_adj = "Невалидно";
          if (_issue.format === "date")
            invalid_adj = "Невалидна";
          if (_issue.format === "time")
            invalid_adj = "Невалидно";
          if (_issue.format === "duration")
            invalid_adj = "Невалидна";
          return `${invalid_adj} ${(_d2 = Nouns[_issue.format]) != null ? _d2 : issue2.format}`;
        }
        case "not_multiple_of":
          return `Невалидно число: трябва да бъде кратно на ${issue2.divisor}`;
        case "unrecognized_keys":
          return `Неразпознат${issue2.keys.length > 1 ? "и" : ""} ключ${issue2.keys.length > 1 ? "ове" : ""}: ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `Невалиден ключ в ${issue2.origin}`;
        case "invalid_union":
          return "Невалиден вход";
        case "invalid_element":
          return `Невалидна стойност в ${issue2.origin}`;
        default:
          return `Невалиден вход`;
      }
    };
  };
  function bg() {
    return {
      localeError: error$F()
    };
  }
  const error$E = () => {
    const Sizable = {
      string: { unit: "caràcters", verb: "contenir" },
      file: { unit: "bytes", verb: "contenir" },
      array: { unit: "elements", verb: "contenir" },
      set: { unit: "elements", verb: "contenir" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "number";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "array";
          }
          if (data === null) {
            return "null";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    const Nouns = {
      regex: "entrada",
      email: "adreça electrònica",
      url: "URL",
      emoji: "emoji",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "data i hora ISO",
      date: "data ISO",
      time: "hora ISO",
      duration: "durada ISO",
      ipv4: "adreça IPv4",
      ipv6: "adreça IPv6",
      cidrv4: "rang IPv4",
      cidrv6: "rang IPv6",
      base64: "cadena codificada en base64",
      base64url: "cadena codificada en base64url",
      json_string: "cadena JSON",
      e164: "número E.164",
      jwt: "JWT",
      template_literal: "entrada"
    };
    return (issue2) => {
      var _a3, _b2, _c2, _d2;
      switch (issue2.code) {
        case "invalid_type":
          return `Tipus invàlid: s'esperava ${issue2.expected}, s'ha rebut ${parsedType2(issue2.input)}`;
        // return `Tipus invàlid: s'esperava ${issue.expected}, s'ha rebut ${util.getParsedType(issue.input)}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `Valor invàlid: s'esperava ${stringifyPrimitive(issue2.values[0])}`;
          return `Opció invàlida: s'esperava una de ${joinValues(issue2.values, " o ")}`;
        case "too_big": {
          const adj = issue2.inclusive ? "com a màxim" : "menys de";
          const sizing = getSizing(issue2.origin);
          if (sizing)
            return `Massa gran: s'esperava que ${(_a3 = issue2.origin) != null ? _a3 : "el valor"} contingués ${adj} ${issue2.maximum.toString()} ${(_b2 = sizing.unit) != null ? _b2 : "elements"}`;
          return `Massa gran: s'esperava que ${(_c2 = issue2.origin) != null ? _c2 : "el valor"} fos ${adj} ${issue2.maximum.toString()}`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? "com a mínim" : "més de";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `Massa petit: s'esperava que ${issue2.origin} contingués ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
          }
          return `Massa petit: s'esperava que ${issue2.origin} fos ${adj} ${issue2.minimum.toString()}`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with") {
            return `Format invàlid: ha de començar amb "${_issue.prefix}"`;
          }
          if (_issue.format === "ends_with")
            return `Format invàlid: ha d'acabar amb "${_issue.suffix}"`;
          if (_issue.format === "includes")
            return `Format invàlid: ha d'incloure "${_issue.includes}"`;
          if (_issue.format === "regex")
            return `Format invàlid: ha de coincidir amb el patró ${_issue.pattern}`;
          return `Format invàlid per a ${(_d2 = Nouns[_issue.format]) != null ? _d2 : issue2.format}`;
        }
        case "not_multiple_of":
          return `Número invàlid: ha de ser múltiple de ${issue2.divisor}`;
        case "unrecognized_keys":
          return `Clau${issue2.keys.length > 1 ? "s" : ""} no reconeguda${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `Clau invàlida a ${issue2.origin}`;
        case "invalid_union":
          return "Entrada invàlida";
        // Could also be "Tipus d'unió invàlid" but "Entrada invàlida" is more general
        case "invalid_element":
          return `Element invàlid a ${issue2.origin}`;
        default:
          return `Entrada invàlida`;
      }
    };
  };
  function ca() {
    return {
      localeError: error$E()
    };
  }
  const error$D = () => {
    const Sizable = {
      string: { unit: "znaků", verb: "mít" },
      file: { unit: "bajtů", verb: "mít" },
      array: { unit: "prvků", verb: "mít" },
      set: { unit: "prvků", verb: "mít" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "číslo";
        }
        case "string": {
          return "řetězec";
        }
        case "boolean": {
          return "boolean";
        }
        case "bigint": {
          return "bigint";
        }
        case "function": {
          return "funkce";
        }
        case "symbol": {
          return "symbol";
        }
        case "undefined": {
          return "undefined";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "pole";
          }
          if (data === null) {
            return "null";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    const Nouns = {
      regex: "regulární výraz",
      email: "e-mailová adresa",
      url: "URL",
      emoji: "emoji",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "datum a čas ve formátu ISO",
      date: "datum ve formátu ISO",
      time: "čas ve formátu ISO",
      duration: "doba trvání ISO",
      ipv4: "IPv4 adresa",
      ipv6: "IPv6 adresa",
      cidrv4: "rozsah IPv4",
      cidrv6: "rozsah IPv6",
      base64: "řetězec zakódovaný ve formátu base64",
      base64url: "řetězec zakódovaný ve formátu base64url",
      json_string: "řetězec ve formátu JSON",
      e164: "číslo E.164",
      jwt: "JWT",
      template_literal: "vstup"
    };
    return (issue2) => {
      var _a3, _b2, _c2, _d2, _e, _f, _g;
      switch (issue2.code) {
        case "invalid_type":
          return `Neplatný vstup: očekáváno ${issue2.expected}, obdrženo ${parsedType2(issue2.input)}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `Neplatný vstup: očekáváno ${stringifyPrimitive(issue2.values[0])}`;
          return `Neplatná možnost: očekávána jedna z hodnot ${joinValues(issue2.values, "|")}`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `Hodnota je příliš velká: ${(_a3 = issue2.origin) != null ? _a3 : "hodnota"} musí mít ${adj}${issue2.maximum.toString()} ${(_b2 = sizing.unit) != null ? _b2 : "prvků"}`;
          }
          return `Hodnota je příliš velká: ${(_c2 = issue2.origin) != null ? _c2 : "hodnota"} musí být ${adj}${issue2.maximum.toString()}`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `Hodnota je příliš malá: ${(_d2 = issue2.origin) != null ? _d2 : "hodnota"} musí mít ${adj}${issue2.minimum.toString()} ${(_e = sizing.unit) != null ? _e : "prvků"}`;
          }
          return `Hodnota je příliš malá: ${(_f = issue2.origin) != null ? _f : "hodnota"} musí být ${adj}${issue2.minimum.toString()}`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with")
            return `Neplatný řetězec: musí začínat na "${_issue.prefix}"`;
          if (_issue.format === "ends_with")
            return `Neplatný řetězec: musí končit na "${_issue.suffix}"`;
          if (_issue.format === "includes")
            return `Neplatný řetězec: musí obsahovat "${_issue.includes}"`;
          if (_issue.format === "regex")
            return `Neplatný řetězec: musí odpovídat vzoru ${_issue.pattern}`;
          return `Neplatný formát ${(_g = Nouns[_issue.format]) != null ? _g : issue2.format}`;
        }
        case "not_multiple_of":
          return `Neplatné číslo: musí být násobkem ${issue2.divisor}`;
        case "unrecognized_keys":
          return `Neznámé klíče: ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `Neplatný klíč v ${issue2.origin}`;
        case "invalid_union":
          return "Neplatný vstup";
        case "invalid_element":
          return `Neplatná hodnota v ${issue2.origin}`;
        default:
          return `Neplatný vstup`;
      }
    };
  };
  function cs() {
    return {
      localeError: error$D()
    };
  }
  const error$C = () => {
    const Sizable = {
      string: { unit: "tegn", verb: "havde" },
      file: { unit: "bytes", verb: "havde" },
      array: { unit: "elementer", verb: "indeholdt" },
      set: { unit: "elementer", verb: "indeholdt" }
    };
    const TypeNames = {
      string: "streng",
      number: "tal",
      boolean: "boolean",
      array: "liste",
      object: "objekt",
      set: "sæt",
      file: "fil"
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    function getTypeName(type2) {
      var _a3;
      return (_a3 = TypeNames[type2]) != null ? _a3 : type2;
    }
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "tal";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "liste";
          }
          if (data === null) {
            return "null";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
          return "objekt";
        }
      }
      return t;
    };
    const Nouns = {
      regex: "input",
      email: "e-mailadresse",
      url: "URL",
      emoji: "emoji",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "ISO dato- og klokkeslæt",
      date: "ISO-dato",
      time: "ISO-klokkeslæt",
      duration: "ISO-varighed",
      ipv4: "IPv4-område",
      ipv6: "IPv6-område",
      cidrv4: "IPv4-spektrum",
      cidrv6: "IPv6-spektrum",
      base64: "base64-kodet streng",
      base64url: "base64url-kodet streng",
      json_string: "JSON-streng",
      e164: "E.164-nummer",
      jwt: "JWT",
      template_literal: "input"
    };
    return (issue2) => {
      var _a3, _b2;
      switch (issue2.code) {
        case "invalid_type":
          return `Ugyldigt input: forventede ${getTypeName(issue2.expected)}, fik ${getTypeName(parsedType2(issue2.input))}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `Ugyldig værdi: forventede ${stringifyPrimitive(issue2.values[0])}`;
          return `Ugyldigt valg: forventede en af følgende ${joinValues(issue2.values, "|")}`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          const origin = getTypeName(issue2.origin);
          if (sizing)
            return `For stor: forventede ${origin != null ? origin : "value"} ${sizing.verb} ${adj} ${issue2.maximum.toString()} ${(_a3 = sizing.unit) != null ? _a3 : "elementer"}`;
          return `For stor: forventede ${origin != null ? origin : "value"} havde ${adj} ${issue2.maximum.toString()}`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          const origin = getTypeName(issue2.origin);
          if (sizing) {
            return `For lille: forventede ${origin} ${sizing.verb} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
          }
          return `For lille: forventede ${origin} havde ${adj} ${issue2.minimum.toString()}`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with")
            return `Ugyldig streng: skal starte med "${_issue.prefix}"`;
          if (_issue.format === "ends_with")
            return `Ugyldig streng: skal ende med "${_issue.suffix}"`;
          if (_issue.format === "includes")
            return `Ugyldig streng: skal indeholde "${_issue.includes}"`;
          if (_issue.format === "regex")
            return `Ugyldig streng: skal matche mønsteret ${_issue.pattern}`;
          return `Ugyldig ${(_b2 = Nouns[_issue.format]) != null ? _b2 : issue2.format}`;
        }
        case "not_multiple_of":
          return `Ugyldigt tal: skal være deleligt med ${issue2.divisor}`;
        case "unrecognized_keys":
          return `${issue2.keys.length > 1 ? "Ukendte nøgler" : "Ukendt nøgle"}: ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `Ugyldig nøgle i ${issue2.origin}`;
        case "invalid_union":
          return "Ugyldigt input: matcher ingen af de tilladte typer";
        case "invalid_element":
          return `Ugyldig værdi i ${issue2.origin}`;
        default:
          return `Ugyldigt input`;
      }
    };
  };
  function da() {
    return {
      localeError: error$C()
    };
  }
  const error$B = () => {
    const Sizable = {
      string: { unit: "Zeichen", verb: "zu haben" },
      file: { unit: "Bytes", verb: "zu haben" },
      array: { unit: "Elemente", verb: "zu haben" },
      set: { unit: "Elemente", verb: "zu haben" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "Zahl";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "Array";
          }
          if (data === null) {
            return "null";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    const Nouns = {
      regex: "Eingabe",
      email: "E-Mail-Adresse",
      url: "URL",
      emoji: "Emoji",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "ISO-Datum und -Uhrzeit",
      date: "ISO-Datum",
      time: "ISO-Uhrzeit",
      duration: "ISO-Dauer",
      ipv4: "IPv4-Adresse",
      ipv6: "IPv6-Adresse",
      cidrv4: "IPv4-Bereich",
      cidrv6: "IPv6-Bereich",
      base64: "Base64-codierter String",
      base64url: "Base64-URL-codierter String",
      json_string: "JSON-String",
      e164: "E.164-Nummer",
      jwt: "JWT",
      template_literal: "Eingabe"
    };
    return (issue2) => {
      var _a3, _b2, _c2, _d2;
      switch (issue2.code) {
        case "invalid_type":
          return `Ungültige Eingabe: erwartet ${issue2.expected}, erhalten ${parsedType2(issue2.input)}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `Ungültige Eingabe: erwartet ${stringifyPrimitive(issue2.values[0])}`;
          return `Ungültige Option: erwartet eine von ${joinValues(issue2.values, "|")}`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          if (sizing)
            return `Zu groß: erwartet, dass ${(_a3 = issue2.origin) != null ? _a3 : "Wert"} ${adj}${issue2.maximum.toString()} ${(_b2 = sizing.unit) != null ? _b2 : "Elemente"} hat`;
          return `Zu groß: erwartet, dass ${(_c2 = issue2.origin) != null ? _c2 : "Wert"} ${adj}${issue2.maximum.toString()} ist`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} hat`;
          }
          return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ist`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with")
            return `Ungültiger String: muss mit "${_issue.prefix}" beginnen`;
          if (_issue.format === "ends_with")
            return `Ungültiger String: muss mit "${_issue.suffix}" enden`;
          if (_issue.format === "includes")
            return `Ungültiger String: muss "${_issue.includes}" enthalten`;
          if (_issue.format === "regex")
            return `Ungültiger String: muss dem Muster ${_issue.pattern} entsprechen`;
          return `Ungültig: ${(_d2 = Nouns[_issue.format]) != null ? _d2 : issue2.format}`;
        }
        case "not_multiple_of":
          return `Ungültige Zahl: muss ein Vielfaches von ${issue2.divisor} sein`;
        case "unrecognized_keys":
          return `${issue2.keys.length > 1 ? "Unbekannte Schlüssel" : "Unbekannter Schlüssel"}: ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `Ungültiger Schlüssel in ${issue2.origin}`;
        case "invalid_union":
          return "Ungültige Eingabe";
        case "invalid_element":
          return `Ungültiger Wert in ${issue2.origin}`;
        default:
          return `Ungültige Eingabe`;
      }
    };
  };
  function de() {
    return {
      localeError: error$B()
    };
  }
  const parsedType$5 = (data) => {
    const t = typeof data;
    switch (t) {
      case "number": {
        return Number.isNaN(data) ? "NaN" : "number";
      }
      case "object": {
        if (Array.isArray(data)) {
          return "array";
        }
        if (data === null) {
          return "null";
        }
        if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
          return data.constructor.name;
        }
      }
    }
    return t;
  };
  const error$A = () => {
    const Sizable = {
      string: { unit: "characters", verb: "to have" },
      file: { unit: "bytes", verb: "to have" },
      array: { unit: "items", verb: "to have" },
      set: { unit: "items", verb: "to have" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const Nouns = {
      regex: "input",
      email: "email address",
      url: "URL",
      emoji: "emoji",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "ISO datetime",
      date: "ISO date",
      time: "ISO time",
      duration: "ISO duration",
      ipv4: "IPv4 address",
      ipv6: "IPv6 address",
      mac: "MAC address",
      cidrv4: "IPv4 range",
      cidrv6: "IPv6 range",
      base64: "base64-encoded string",
      base64url: "base64url-encoded string",
      json_string: "JSON string",
      e164: "E.164 number",
      jwt: "JWT",
      template_literal: "input"
    };
    return (issue2) => {
      var _a3, _b2, _c2, _d2;
      switch (issue2.code) {
        case "invalid_type":
          return `Invalid input: expected ${issue2.expected}, received ${parsedType$5(issue2.input)}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`;
          return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          if (sizing)
            return `Too big: expected ${(_a3 = issue2.origin) != null ? _a3 : "value"} to have ${adj}${issue2.maximum.toString()} ${(_b2 = sizing.unit) != null ? _b2 : "elements"}`;
          return `Too big: expected ${(_c2 = issue2.origin) != null ? _c2 : "value"} to be ${adj}${issue2.maximum.toString()}`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
          }
          return `Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with") {
            return `Invalid string: must start with "${_issue.prefix}"`;
          }
          if (_issue.format === "ends_with")
            return `Invalid string: must end with "${_issue.suffix}"`;
          if (_issue.format === "includes")
            return `Invalid string: must include "${_issue.includes}"`;
          if (_issue.format === "regex")
            return `Invalid string: must match pattern ${_issue.pattern}`;
          return `Invalid ${(_d2 = Nouns[_issue.format]) != null ? _d2 : issue2.format}`;
        }
        case "not_multiple_of":
          return `Invalid number: must be a multiple of ${issue2.divisor}`;
        case "unrecognized_keys":
          return `Unrecognized key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `Invalid key in ${issue2.origin}`;
        case "invalid_union":
          return "Invalid input";
        case "invalid_element":
          return `Invalid value in ${issue2.origin}`;
        default:
          return `Invalid input`;
      }
    };
  };
  function en() {
    return {
      localeError: error$A()
    };
  }
  const parsedType$4 = (data) => {
    const t = typeof data;
    switch (t) {
      case "number": {
        return Number.isNaN(data) ? "NaN" : "nombro";
      }
      case "object": {
        if (Array.isArray(data)) {
          return "tabelo";
        }
        if (data === null) {
          return "senvalora";
        }
        if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
          return data.constructor.name;
        }
      }
    }
    return t;
  };
  const error$z = () => {
    const Sizable = {
      string: { unit: "karaktrojn", verb: "havi" },
      file: { unit: "bajtojn", verb: "havi" },
      array: { unit: "elementojn", verb: "havi" },
      set: { unit: "elementojn", verb: "havi" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const Nouns = {
      regex: "enigo",
      email: "retadreso",
      url: "URL",
      emoji: "emoĝio",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "ISO-datotempo",
      date: "ISO-dato",
      time: "ISO-tempo",
      duration: "ISO-daŭro",
      ipv4: "IPv4-adreso",
      ipv6: "IPv6-adreso",
      cidrv4: "IPv4-rango",
      cidrv6: "IPv6-rango",
      base64: "64-ume kodita karaktraro",
      base64url: "URL-64-ume kodita karaktraro",
      json_string: "JSON-karaktraro",
      e164: "E.164-nombro",
      jwt: "JWT",
      template_literal: "enigo"
    };
    return (issue2) => {
      var _a3, _b2, _c2, _d2;
      switch (issue2.code) {
        case "invalid_type":
          return `Nevalida enigo: atendiĝis ${issue2.expected}, riceviĝis ${parsedType$4(issue2.input)}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `Nevalida enigo: atendiĝis ${stringifyPrimitive(issue2.values[0])}`;
          return `Nevalida opcio: atendiĝis unu el ${joinValues(issue2.values, "|")}`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          if (sizing)
            return `Tro granda: atendiĝis ke ${(_a3 = issue2.origin) != null ? _a3 : "valoro"} havu ${adj}${issue2.maximum.toString()} ${(_b2 = sizing.unit) != null ? _b2 : "elementojn"}`;
          return `Tro granda: atendiĝis ke ${(_c2 = issue2.origin) != null ? _c2 : "valoro"} havu ${adj}${issue2.maximum.toString()}`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `Tro malgranda: atendiĝis ke ${issue2.origin} havu ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
          }
          return `Tro malgranda: atendiĝis ke ${issue2.origin} estu ${adj}${issue2.minimum.toString()}`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with")
            return `Nevalida karaktraro: devas komenciĝi per "${_issue.prefix}"`;
          if (_issue.format === "ends_with")
            return `Nevalida karaktraro: devas finiĝi per "${_issue.suffix}"`;
          if (_issue.format === "includes")
            return `Nevalida karaktraro: devas inkluzivi "${_issue.includes}"`;
          if (_issue.format === "regex")
            return `Nevalida karaktraro: devas kongrui kun la modelo ${_issue.pattern}`;
          return `Nevalida ${(_d2 = Nouns[_issue.format]) != null ? _d2 : issue2.format}`;
        }
        case "not_multiple_of":
          return `Nevalida nombro: devas esti oblo de ${issue2.divisor}`;
        case "unrecognized_keys":
          return `Nekonata${issue2.keys.length > 1 ? "j" : ""} ŝlosilo${issue2.keys.length > 1 ? "j" : ""}: ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `Nevalida ŝlosilo en ${issue2.origin}`;
        case "invalid_union":
          return "Nevalida enigo";
        case "invalid_element":
          return `Nevalida valoro en ${issue2.origin}`;
        default:
          return `Nevalida enigo`;
      }
    };
  };
  function eo() {
    return {
      localeError: error$z()
    };
  }
  const error$y = () => {
    const Sizable = {
      string: { unit: "caracteres", verb: "tener" },
      file: { unit: "bytes", verb: "tener" },
      array: { unit: "elementos", verb: "tener" },
      set: { unit: "elementos", verb: "tener" }
    };
    const TypeNames = {
      string: "texto",
      number: "número",
      boolean: "booleano",
      array: "arreglo",
      object: "objeto",
      set: "conjunto",
      file: "archivo",
      date: "fecha",
      bigint: "número grande",
      symbol: "símbolo",
      undefined: "indefinido",
      null: "nulo",
      function: "función",
      map: "mapa",
      record: "registro",
      tuple: "tupla",
      enum: "enumeración",
      union: "unión",
      literal: "literal",
      promise: "promesa",
      void: "vacío",
      never: "nunca",
      unknown: "desconocido",
      any: "cualquiera"
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    function getTypeName(type2) {
      var _a3;
      return (_a3 = TypeNames[type2]) != null ? _a3 : type2;
    }
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "number";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "array";
          }
          if (data === null) {
            return "null";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype) {
            return data.constructor.name;
          }
          return "object";
        }
      }
      return t;
    };
    const Nouns = {
      regex: "entrada",
      email: "dirección de correo electrónico",
      url: "URL",
      emoji: "emoji",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "fecha y hora ISO",
      date: "fecha ISO",
      time: "hora ISO",
      duration: "duración ISO",
      ipv4: "dirección IPv4",
      ipv6: "dirección IPv6",
      cidrv4: "rango IPv4",
      cidrv6: "rango IPv6",
      base64: "cadena codificada en base64",
      base64url: "URL codificada en base64",
      json_string: "cadena JSON",
      e164: "número E.164",
      jwt: "JWT",
      template_literal: "entrada"
    };
    return (issue2) => {
      var _a3, _b2;
      switch (issue2.code) {
        case "invalid_type":
          return `Entrada inválida: se esperaba ${getTypeName(issue2.expected)}, recibido ${getTypeName(parsedType2(issue2.input))}`;
        // return `Entrada inválida: se esperaba ${issue.expected}, recibido ${util.getParsedType(issue.input)}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `Entrada inválida: se esperaba ${stringifyPrimitive(issue2.values[0])}`;
          return `Opción inválida: se esperaba una de ${joinValues(issue2.values, "|")}`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          const origin = getTypeName(issue2.origin);
          if (sizing)
            return `Demasiado grande: se esperaba que ${origin != null ? origin : "valor"} tuviera ${adj}${issue2.maximum.toString()} ${(_a3 = sizing.unit) != null ? _a3 : "elementos"}`;
          return `Demasiado grande: se esperaba que ${origin != null ? origin : "valor"} fuera ${adj}${issue2.maximum.toString()}`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          const origin = getTypeName(issue2.origin);
          if (sizing) {
            return `Demasiado pequeño: se esperaba que ${origin} tuviera ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
          }
          return `Demasiado pequeño: se esperaba que ${origin} fuera ${adj}${issue2.minimum.toString()}`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with")
            return `Cadena inválida: debe comenzar con "${_issue.prefix}"`;
          if (_issue.format === "ends_with")
            return `Cadena inválida: debe terminar en "${_issue.suffix}"`;
          if (_issue.format === "includes")
            return `Cadena inválida: debe incluir "${_issue.includes}"`;
          if (_issue.format === "regex")
            return `Cadena inválida: debe coincidir con el patrón ${_issue.pattern}`;
          return `Inválido ${(_b2 = Nouns[_issue.format]) != null ? _b2 : issue2.format}`;
        }
        case "not_multiple_of":
          return `Número inválido: debe ser múltiplo de ${issue2.divisor}`;
        case "unrecognized_keys":
          return `Llave${issue2.keys.length > 1 ? "s" : ""} desconocida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `Llave inválida en ${getTypeName(issue2.origin)}`;
        case "invalid_union":
          return "Entrada inválida";
        case "invalid_element":
          return `Valor inválido en ${getTypeName(issue2.origin)}`;
        default:
          return `Entrada inválida`;
      }
    };
  };
  function es() {
    return {
      localeError: error$y()
    };
  }
  const error$x = () => {
    const Sizable = {
      string: { unit: "کاراکتر", verb: "داشته باشد" },
      file: { unit: "بایت", verb: "داشته باشد" },
      array: { unit: "آیتم", verb: "داشته باشد" },
      set: { unit: "آیتم", verb: "داشته باشد" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "عدد";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "آرایه";
          }
          if (data === null) {
            return "null";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    const Nouns = {
      regex: "ورودی",
      email: "آدرس ایمیل",
      url: "URL",
      emoji: "ایموجی",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "تاریخ و زمان ایزو",
      date: "تاریخ ایزو",
      time: "زمان ایزو",
      duration: "مدت زمان ایزو",
      ipv4: "IPv4 آدرس",
      ipv6: "IPv6 آدرس",
      cidrv4: "IPv4 دامنه",
      cidrv6: "IPv6 دامنه",
      base64: "base64-encoded رشته",
      base64url: "base64url-encoded رشته",
      json_string: "JSON رشته",
      e164: "E.164 عدد",
      jwt: "JWT",
      template_literal: "ورودی"
    };
    return (issue2) => {
      var _a3, _b2, _c2, _d2;
      switch (issue2.code) {
        case "invalid_type":
          return `ورودی نامعتبر: می‌بایست ${issue2.expected} می‌بود، ${parsedType2(issue2.input)} دریافت شد`;
        case "invalid_value":
          if (issue2.values.length === 1) {
            return `ورودی نامعتبر: می‌بایست ${stringifyPrimitive(issue2.values[0])} می‌بود`;
          }
          return `گزینه نامعتبر: می‌بایست یکی از ${joinValues(issue2.values, "|")} می‌بود`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `خیلی بزرگ: ${(_a3 = issue2.origin) != null ? _a3 : "مقدار"} باید ${adj}${issue2.maximum.toString()} ${(_b2 = sizing.unit) != null ? _b2 : "عنصر"} باشد`;
          }
          return `خیلی بزرگ: ${(_c2 = issue2.origin) != null ? _c2 : "مقدار"} باید ${adj}${issue2.maximum.toString()} باشد`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `خیلی کوچک: ${issue2.origin} باید ${adj}${issue2.minimum.toString()} ${sizing.unit} باشد`;
          }
          return `خیلی کوچک: ${issue2.origin} باید ${adj}${issue2.minimum.toString()} باشد`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with") {
            return `رشته نامعتبر: باید با "${_issue.prefix}" شروع شود`;
          }
          if (_issue.format === "ends_with") {
            return `رشته نامعتبر: باید با "${_issue.suffix}" تمام شود`;
          }
          if (_issue.format === "includes") {
            return `رشته نامعتبر: باید شامل "${_issue.includes}" باشد`;
          }
          if (_issue.format === "regex") {
            return `رشته نامعتبر: باید با الگوی ${_issue.pattern} مطابقت داشته باشد`;
          }
          return `${(_d2 = Nouns[_issue.format]) != null ? _d2 : issue2.format} نامعتبر`;
        }
        case "not_multiple_of":
          return `عدد نامعتبر: باید مضرب ${issue2.divisor} باشد`;
        case "unrecognized_keys":
          return `کلید${issue2.keys.length > 1 ? "های" : ""} ناشناس: ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `کلید ناشناس در ${issue2.origin}`;
        case "invalid_union":
          return `ورودی نامعتبر`;
        case "invalid_element":
          return `مقدار نامعتبر در ${issue2.origin}`;
        default:
          return `ورودی نامعتبر`;
      }
    };
  };
  function fa() {
    return {
      localeError: error$x()
    };
  }
  const error$w = () => {
    const Sizable = {
      string: { unit: "merkkiä", subject: "merkkijonon" },
      file: { unit: "tavua", subject: "tiedoston" },
      array: { unit: "alkiota", subject: "listan" },
      set: { unit: "alkiota", subject: "joukon" },
      number: { unit: "", subject: "luvun" },
      bigint: { unit: "", subject: "suuren kokonaisluvun" },
      int: { unit: "", subject: "kokonaisluvun" },
      date: { unit: "", subject: "päivämäärän" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "number";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "array";
          }
          if (data === null) {
            return "null";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    const Nouns = {
      regex: "säännöllinen lauseke",
      email: "sähköpostiosoite",
      url: "URL-osoite",
      emoji: "emoji",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "ISO-aikaleima",
      date: "ISO-päivämäärä",
      time: "ISO-aika",
      duration: "ISO-kesto",
      ipv4: "IPv4-osoite",
      ipv6: "IPv6-osoite",
      cidrv4: "IPv4-alue",
      cidrv6: "IPv6-alue",
      base64: "base64-koodattu merkkijono",
      base64url: "base64url-koodattu merkkijono",
      json_string: "JSON-merkkijono",
      e164: "E.164-luku",
      jwt: "JWT",
      template_literal: "templaattimerkkijono"
    };
    return (issue2) => {
      var _a3;
      switch (issue2.code) {
        case "invalid_type":
          return `Virheellinen tyyppi: odotettiin ${issue2.expected}, oli ${parsedType2(issue2.input)}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `Virheellinen syöte: täytyy olla ${stringifyPrimitive(issue2.values[0])}`;
          return `Virheellinen valinta: täytyy olla yksi seuraavista: ${joinValues(issue2.values, "|")}`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `Liian suuri: ${sizing.subject} täytyy olla ${adj}${issue2.maximum.toString()} ${sizing.unit}`.trim();
          }
          return `Liian suuri: arvon täytyy olla ${adj}${issue2.maximum.toString()}`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `Liian pieni: ${sizing.subject} täytyy olla ${adj}${issue2.minimum.toString()} ${sizing.unit}`.trim();
          }
          return `Liian pieni: arvon täytyy olla ${adj}${issue2.minimum.toString()}`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with")
            return `Virheellinen syöte: täytyy alkaa "${_issue.prefix}"`;
          if (_issue.format === "ends_with")
            return `Virheellinen syöte: täytyy loppua "${_issue.suffix}"`;
          if (_issue.format === "includes")
            return `Virheellinen syöte: täytyy sisältää "${_issue.includes}"`;
          if (_issue.format === "regex") {
            return `Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${_issue.pattern}`;
          }
          return `Virheellinen ${(_a3 = Nouns[_issue.format]) != null ? _a3 : issue2.format}`;
        }
        case "not_multiple_of":
          return `Virheellinen luku: täytyy olla luvun ${issue2.divisor} monikerta`;
        case "unrecognized_keys":
          return `${issue2.keys.length > 1 ? "Tuntemattomat avaimet" : "Tuntematon avain"}: ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return "Virheellinen avain tietueessa";
        case "invalid_union":
          return "Virheellinen unioni";
        case "invalid_element":
          return "Virheellinen arvo joukossa";
        default:
          return `Virheellinen syöte`;
      }
    };
  };
  function fi() {
    return {
      localeError: error$w()
    };
  }
  const error$v = () => {
    const Sizable = {
      string: { unit: "caractères", verb: "avoir" },
      file: { unit: "octets", verb: "avoir" },
      array: { unit: "éléments", verb: "avoir" },
      set: { unit: "éléments", verb: "avoir" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "nombre";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "tableau";
          }
          if (data === null) {
            return "null";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    const Nouns = {
      regex: "entrée",
      email: "adresse e-mail",
      url: "URL",
      emoji: "emoji",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "date et heure ISO",
      date: "date ISO",
      time: "heure ISO",
      duration: "durée ISO",
      ipv4: "adresse IPv4",
      ipv6: "adresse IPv6",
      cidrv4: "plage IPv4",
      cidrv6: "plage IPv6",
      base64: "chaîne encodée en base64",
      base64url: "chaîne encodée en base64url",
      json_string: "chaîne JSON",
      e164: "numéro E.164",
      jwt: "JWT",
      template_literal: "entrée"
    };
    return (issue2) => {
      var _a3, _b2, _c2, _d2;
      switch (issue2.code) {
        case "invalid_type":
          return `Entrée invalide : ${issue2.expected} attendu, ${parsedType2(issue2.input)} reçu`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `Entrée invalide : ${stringifyPrimitive(issue2.values[0])} attendu`;
          return `Option invalide : une valeur parmi ${joinValues(issue2.values, "|")} attendue`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          if (sizing)
            return `Trop grand : ${(_a3 = issue2.origin) != null ? _a3 : "valeur"} doit ${sizing.verb} ${adj}${issue2.maximum.toString()} ${(_b2 = sizing.unit) != null ? _b2 : "élément(s)"}`;
          return `Trop grand : ${(_c2 = issue2.origin) != null ? _c2 : "valeur"} doit être ${adj}${issue2.maximum.toString()}`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `Trop petit : ${issue2.origin} doit ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
          }
          return `Trop petit : ${issue2.origin} doit être ${adj}${issue2.minimum.toString()}`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with")
            return `Chaîne invalide : doit commencer par "${_issue.prefix}"`;
          if (_issue.format === "ends_with")
            return `Chaîne invalide : doit se terminer par "${_issue.suffix}"`;
          if (_issue.format === "includes")
            return `Chaîne invalide : doit inclure "${_issue.includes}"`;
          if (_issue.format === "regex")
            return `Chaîne invalide : doit correspondre au modèle ${_issue.pattern}`;
          return `${(_d2 = Nouns[_issue.format]) != null ? _d2 : issue2.format} invalide`;
        }
        case "not_multiple_of":
          return `Nombre invalide : doit être un multiple de ${issue2.divisor}`;
        case "unrecognized_keys":
          return `Clé${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `Clé invalide dans ${issue2.origin}`;
        case "invalid_union":
          return "Entrée invalide";
        case "invalid_element":
          return `Valeur invalide dans ${issue2.origin}`;
        default:
          return `Entrée invalide`;
      }
    };
  };
  function fr() {
    return {
      localeError: error$v()
    };
  }
  const error$u = () => {
    const Sizable = {
      string: { unit: "caractères", verb: "avoir" },
      file: { unit: "octets", verb: "avoir" },
      array: { unit: "éléments", verb: "avoir" },
      set: { unit: "éléments", verb: "avoir" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "number";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "array";
          }
          if (data === null) {
            return "null";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    const Nouns = {
      regex: "entrée",
      email: "adresse courriel",
      url: "URL",
      emoji: "emoji",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "date-heure ISO",
      date: "date ISO",
      time: "heure ISO",
      duration: "durée ISO",
      ipv4: "adresse IPv4",
      ipv6: "adresse IPv6",
      cidrv4: "plage IPv4",
      cidrv6: "plage IPv6",
      base64: "chaîne encodée en base64",
      base64url: "chaîne encodée en base64url",
      json_string: "chaîne JSON",
      e164: "numéro E.164",
      jwt: "JWT",
      template_literal: "entrée"
    };
    return (issue2) => {
      var _a3, _b2, _c2;
      switch (issue2.code) {
        case "invalid_type":
          return `Entrée invalide : attendu ${issue2.expected}, reçu ${parsedType2(issue2.input)}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `Entrée invalide : attendu ${stringifyPrimitive(issue2.values[0])}`;
          return `Option invalide : attendu l'une des valeurs suivantes ${joinValues(issue2.values, "|")}`;
        case "too_big": {
          const adj = issue2.inclusive ? "≤" : "<";
          const sizing = getSizing(issue2.origin);
          if (sizing)
            return `Trop grand : attendu que ${(_a3 = issue2.origin) != null ? _a3 : "la valeur"} ait ${adj}${issue2.maximum.toString()} ${sizing.unit}`;
          return `Trop grand : attendu que ${(_b2 = issue2.origin) != null ? _b2 : "la valeur"} soit ${adj}${issue2.maximum.toString()}`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? "≥" : ">";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `Trop petit : attendu que ${issue2.origin} ait ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
          }
          return `Trop petit : attendu que ${issue2.origin} soit ${adj}${issue2.minimum.toString()}`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with") {
            return `Chaîne invalide : doit commencer par "${_issue.prefix}"`;
          }
          if (_issue.format === "ends_with")
            return `Chaîne invalide : doit se terminer par "${_issue.suffix}"`;
          if (_issue.format === "includes")
            return `Chaîne invalide : doit inclure "${_issue.includes}"`;
          if (_issue.format === "regex")
            return `Chaîne invalide : doit correspondre au motif ${_issue.pattern}`;
          return `${(_c2 = Nouns[_issue.format]) != null ? _c2 : issue2.format} invalide`;
        }
        case "not_multiple_of":
          return `Nombre invalide : doit être un multiple de ${issue2.divisor}`;
        case "unrecognized_keys":
          return `Clé${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `Clé invalide dans ${issue2.origin}`;
        case "invalid_union":
          return "Entrée invalide";
        case "invalid_element":
          return `Valeur invalide dans ${issue2.origin}`;
        default:
          return `Entrée invalide`;
      }
    };
  };
  function frCA() {
    return {
      localeError: error$u()
    };
  }
  const error$t = () => {
    const TypeNames = {
      string: { label: "מחרוזת", gender: "f" },
      number: { label: "מספר", gender: "m" },
      boolean: { label: "ערך בוליאני", gender: "m" },
      bigint: { label: "BigInt", gender: "m" },
      date: { label: "תאריך", gender: "m" },
      array: { label: "מערך", gender: "m" },
      object: { label: "אובייקט", gender: "m" },
      null: { label: "ערך ריק (null)", gender: "m" },
      undefined: { label: "ערך לא מוגדר (undefined)", gender: "m" },
      symbol: { label: "סימבול (Symbol)", gender: "m" },
      function: { label: "פונקציה", gender: "f" },
      map: { label: "מפה (Map)", gender: "f" },
      set: { label: "קבוצה (Set)", gender: "f" },
      file: { label: "קובץ", gender: "m" },
      promise: { label: "Promise", gender: "m" },
      NaN: { label: "NaN", gender: "m" },
      unknown: { label: "ערך לא ידוע", gender: "m" },
      value: { label: "ערך", gender: "m" }
    };
    const Sizable = {
      string: { unit: "תווים", shortLabel: "קצר", longLabel: "ארוך" },
      file: { unit: "בייטים", shortLabel: "קטן", longLabel: "גדול" },
      array: { unit: "פריטים", shortLabel: "קטן", longLabel: "גדול" },
      set: { unit: "פריטים", shortLabel: "קטן", longLabel: "גדול" },
      number: { unit: "", shortLabel: "קטן", longLabel: "גדול" }
      // no unit
    };
    const typeEntry = (t) => t ? TypeNames[t] : void 0;
    const typeLabel = (t) => {
      const e = typeEntry(t);
      if (e)
        return e.label;
      return t != null ? t : TypeNames.unknown.label;
    };
    const withDefinite = (t) => `ה${typeLabel(t)}`;
    const verbFor = (t) => {
      var _a3;
      const e = typeEntry(t);
      const gender = (_a3 = e == null ? void 0 : e.gender) != null ? _a3 : "m";
      return gender === "f" ? "צריכה להיות" : "צריך להיות";
    };
    const getSizing = (origin) => {
      var _a3;
      if (!origin)
        return null;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    };
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number":
          return Number.isNaN(data) ? "NaN" : "number";
        case "object": {
          if (Array.isArray(data))
            return "array";
          if (data === null)
            return "null";
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
          return "object";
        }
        default:
          return t;
      }
    };
    const Nouns = {
      regex: { label: "קלט", gender: "m" },
      email: { label: "כתובת אימייל", gender: "f" },
      url: { label: "כתובת רשת", gender: "f" },
      emoji: { label: "אימוג'י", gender: "m" },
      uuid: { label: "UUID", gender: "m" },
      nanoid: { label: "nanoid", gender: "m" },
      guid: { label: "GUID", gender: "m" },
      cuid: { label: "cuid", gender: "m" },
      cuid2: { label: "cuid2", gender: "m" },
      ulid: { label: "ULID", gender: "m" },
      xid: { label: "XID", gender: "m" },
      ksuid: { label: "KSUID", gender: "m" },
      datetime: { label: "תאריך וזמן ISO", gender: "m" },
      date: { label: "תאריך ISO", gender: "m" },
      time: { label: "זמן ISO", gender: "m" },
      duration: { label: "משך זמן ISO", gender: "m" },
      ipv4: { label: "כתובת IPv4", gender: "f" },
      ipv6: { label: "כתובת IPv6", gender: "f" },
      cidrv4: { label: "טווח IPv4", gender: "m" },
      cidrv6: { label: "טווח IPv6", gender: "m" },
      base64: { label: "מחרוזת בבסיס 64", gender: "f" },
      base64url: { label: "מחרוזת בבסיס 64 לכתובות רשת", gender: "f" },
      json_string: { label: "מחרוזת JSON", gender: "f" },
      e164: { label: "מספר E.164", gender: "m" },
      jwt: { label: "JWT", gender: "m" },
      ends_with: { label: "קלט", gender: "m" },
      includes: { label: "קלט", gender: "m" },
      lowercase: { label: "קלט", gender: "m" },
      starts_with: { label: "קלט", gender: "m" },
      uppercase: { label: "קלט", gender: "m" }
    };
    return (issue2) => {
      var _a3, _b2, _c2, _d2, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s;
      switch (issue2.code) {
        case "invalid_type": {
          const expectedKey = issue2.expected;
          const expected = typeLabel(expectedKey);
          const receivedKey = parsedType2(issue2.input);
          const received = (_b2 = (_a3 = TypeNames[receivedKey]) == null ? void 0 : _a3.label) != null ? _b2 : receivedKey;
          return `קלט לא תקין: צריך להיות ${expected}, התקבל ${received}`;
        }
        case "invalid_value": {
          if (issue2.values.length === 1) {
            return `ערך לא תקין: הערך חייב להיות ${stringifyPrimitive(issue2.values[0])}`;
          }
          const stringified = issue2.values.map((v) => stringifyPrimitive(v));
          if (issue2.values.length === 2) {
            return `ערך לא תקין: האפשרויות המתאימות הן ${stringified[0]} או ${stringified[1]}`;
          }
          const lastValue = stringified[stringified.length - 1];
          const restValues = stringified.slice(0, -1).join(", ");
          return `ערך לא תקין: האפשרויות המתאימות הן ${restValues} או ${lastValue}`;
        }
        case "too_big": {
          const sizing = getSizing(issue2.origin);
          const subject = withDefinite((_c2 = issue2.origin) != null ? _c2 : "value");
          if (issue2.origin === "string") {
            return `${(_d2 = sizing == null ? void 0 : sizing.longLabel) != null ? _d2 : "ארוך"} מדי: ${subject} צריכה להכיל ${issue2.maximum.toString()} ${(_e = sizing == null ? void 0 : sizing.unit) != null ? _e : ""} ${issue2.inclusive ? "או פחות" : "לכל היותר"}`.trim();
          }
          if (issue2.origin === "number") {
            const comparison = issue2.inclusive ? `קטן או שווה ל-${issue2.maximum}` : `קטן מ-${issue2.maximum}`;
            return `גדול מדי: ${subject} צריך להיות ${comparison}`;
          }
          if (issue2.origin === "array" || issue2.origin === "set") {
            const verb = issue2.origin === "set" ? "צריכה" : "צריך";
            const comparison = issue2.inclusive ? `${issue2.maximum} ${(_f = sizing == null ? void 0 : sizing.unit) != null ? _f : ""} או פחות` : `פחות מ-${issue2.maximum} ${(_g = sizing == null ? void 0 : sizing.unit) != null ? _g : ""}`;
            return `גדול מדי: ${subject} ${verb} להכיל ${comparison}`.trim();
          }
          const adj = issue2.inclusive ? "<=" : "<";
          const be2 = verbFor((_h = issue2.origin) != null ? _h : "value");
          if (sizing == null ? void 0 : sizing.unit) {
            return `${sizing.longLabel} מדי: ${subject} ${be2} ${adj}${issue2.maximum.toString()} ${sizing.unit}`;
          }
          return `${(_i = sizing == null ? void 0 : sizing.longLabel) != null ? _i : "גדול"} מדי: ${subject} ${be2} ${adj}${issue2.maximum.toString()}`;
        }
        case "too_small": {
          const sizing = getSizing(issue2.origin);
          const subject = withDefinite((_j = issue2.origin) != null ? _j : "value");
          if (issue2.origin === "string") {
            return `${(_k = sizing == null ? void 0 : sizing.shortLabel) != null ? _k : "קצר"} מדי: ${subject} צריכה להכיל ${issue2.minimum.toString()} ${(_l = sizing == null ? void 0 : sizing.unit) != null ? _l : ""} ${issue2.inclusive ? "או יותר" : "לפחות"}`.trim();
          }
          if (issue2.origin === "number") {
            const comparison = issue2.inclusive ? `גדול או שווה ל-${issue2.minimum}` : `גדול מ-${issue2.minimum}`;
            return `קטן מדי: ${subject} צריך להיות ${comparison}`;
          }
          if (issue2.origin === "array" || issue2.origin === "set") {
            const verb = issue2.origin === "set" ? "צריכה" : "צריך";
            if (issue2.minimum === 1 && issue2.inclusive) {
              const singularPhrase = issue2.origin === "set" ? "לפחות פריט אחד" : "לפחות פריט אחד";
              return `קטן מדי: ${subject} ${verb} להכיל ${singularPhrase}`;
            }
            const comparison = issue2.inclusive ? `${issue2.minimum} ${(_m = sizing == null ? void 0 : sizing.unit) != null ? _m : ""} או יותר` : `יותר מ-${issue2.minimum} ${(_n = sizing == null ? void 0 : sizing.unit) != null ? _n : ""}`;
            return `קטן מדי: ${subject} ${verb} להכיל ${comparison}`.trim();
          }
          const adj = issue2.inclusive ? ">=" : ">";
          const be2 = verbFor((_o = issue2.origin) != null ? _o : "value");
          if (sizing == null ? void 0 : sizing.unit) {
            return `${sizing.shortLabel} מדי: ${subject} ${be2} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
          }
          return `${(_p = sizing == null ? void 0 : sizing.shortLabel) != null ? _p : "קטן"} מדי: ${subject} ${be2} ${adj}${issue2.minimum.toString()}`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with")
            return `המחרוזת חייבת להתחיל ב "${_issue.prefix}"`;
          if (_issue.format === "ends_with")
            return `המחרוזת חייבת להסתיים ב "${_issue.suffix}"`;
          if (_issue.format === "includes")
            return `המחרוזת חייבת לכלול "${_issue.includes}"`;
          if (_issue.format === "regex")
            return `המחרוזת חייבת להתאים לתבנית ${_issue.pattern}`;
          const nounEntry = Nouns[_issue.format];
          const noun = (_q = nounEntry == null ? void 0 : nounEntry.label) != null ? _q : _issue.format;
          const gender = (_r = nounEntry == null ? void 0 : nounEntry.gender) != null ? _r : "m";
          const adjective = gender === "f" ? "תקינה" : "תקין";
          return `${noun} לא ${adjective}`;
        }
        case "not_multiple_of":
          return `מספר לא תקין: חייב להיות מכפלה של ${issue2.divisor}`;
        case "unrecognized_keys":
          return `מפתח${issue2.keys.length > 1 ? "ות" : ""} לא מזוה${issue2.keys.length > 1 ? "ים" : "ה"}: ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key": {
          return `שדה לא תקין באובייקט`;
        }
        case "invalid_union":
          return "קלט לא תקין";
        case "invalid_element": {
          const place = withDefinite((_s = issue2.origin) != null ? _s : "array");
          return `ערך לא תקין ב${place}`;
        }
        default:
          return `קלט לא תקין`;
      }
    };
  };
  function he() {
    return {
      localeError: error$t()
    };
  }
  const error$s = () => {
    const Sizable = {
      string: { unit: "karakter", verb: "legyen" },
      file: { unit: "byte", verb: "legyen" },
      array: { unit: "elem", verb: "legyen" },
      set: { unit: "elem", verb: "legyen" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "szám";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "tömb";
          }
          if (data === null) {
            return "null";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    const Nouns = {
      regex: "bemenet",
      email: "email cím",
      url: "URL",
      emoji: "emoji",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "ISO időbélyeg",
      date: "ISO dátum",
      time: "ISO idő",
      duration: "ISO időintervallum",
      ipv4: "IPv4 cím",
      ipv6: "IPv6 cím",
      cidrv4: "IPv4 tartomány",
      cidrv6: "IPv6 tartomány",
      base64: "base64-kódolt string",
      base64url: "base64url-kódolt string",
      json_string: "JSON string",
      e164: "E.164 szám",
      jwt: "JWT",
      template_literal: "bemenet"
    };
    return (issue2) => {
      var _a3, _b2, _c2, _d2;
      switch (issue2.code) {
        case "invalid_type":
          return `Érvénytelen bemenet: a várt érték ${issue2.expected}, a kapott érték ${parsedType2(issue2.input)}`;
        // return `Invalid input: expected ${issue.expected}, received ${util.getParsedType(issue.input)}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `Érvénytelen bemenet: a várt érték ${stringifyPrimitive(issue2.values[0])}`;
          return `Érvénytelen opció: valamelyik érték várt ${joinValues(issue2.values, "|")}`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          if (sizing)
            return `Túl nagy: ${(_a3 = issue2.origin) != null ? _a3 : "érték"} mérete túl nagy ${adj}${issue2.maximum.toString()} ${(_b2 = sizing.unit) != null ? _b2 : "elem"}`;
          return `Túl nagy: a bemeneti érték ${(_c2 = issue2.origin) != null ? _c2 : "érték"} túl nagy: ${adj}${issue2.maximum.toString()}`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `Túl kicsi: a bemeneti érték ${issue2.origin} mérete túl kicsi ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
          }
          return `Túl kicsi: a bemeneti érték ${issue2.origin} túl kicsi ${adj}${issue2.minimum.toString()}`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with")
            return `Érvénytelen string: "${_issue.prefix}" értékkel kell kezdődnie`;
          if (_issue.format === "ends_with")
            return `Érvénytelen string: "${_issue.suffix}" értékkel kell végződnie`;
          if (_issue.format === "includes")
            return `Érvénytelen string: "${_issue.includes}" értéket kell tartalmaznia`;
          if (_issue.format === "regex")
            return `Érvénytelen string: ${_issue.pattern} mintának kell megfelelnie`;
          return `Érvénytelen ${(_d2 = Nouns[_issue.format]) != null ? _d2 : issue2.format}`;
        }
        case "not_multiple_of":
          return `Érvénytelen szám: ${issue2.divisor} többszörösének kell lennie`;
        case "unrecognized_keys":
          return `Ismeretlen kulcs${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `Érvénytelen kulcs ${issue2.origin}`;
        case "invalid_union":
          return "Érvénytelen bemenet";
        case "invalid_element":
          return `Érvénytelen érték: ${issue2.origin}`;
        default:
          return `Érvénytelen bemenet`;
      }
    };
  };
  function hu() {
    return {
      localeError: error$s()
    };
  }
  const error$r = () => {
    const Sizable = {
      string: { unit: "karakter", verb: "memiliki" },
      file: { unit: "byte", verb: "memiliki" },
      array: { unit: "item", verb: "memiliki" },
      set: { unit: "item", verb: "memiliki" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "number";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "array";
          }
          if (data === null) {
            return "null";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    const Nouns = {
      regex: "input",
      email: "alamat email",
      url: "URL",
      emoji: "emoji",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "tanggal dan waktu format ISO",
      date: "tanggal format ISO",
      time: "jam format ISO",
      duration: "durasi format ISO",
      ipv4: "alamat IPv4",
      ipv6: "alamat IPv6",
      cidrv4: "rentang alamat IPv4",
      cidrv6: "rentang alamat IPv6",
      base64: "string dengan enkode base64",
      base64url: "string dengan enkode base64url",
      json_string: "string JSON",
      e164: "angka E.164",
      jwt: "JWT",
      template_literal: "input"
    };
    return (issue2) => {
      var _a3, _b2, _c2, _d2;
      switch (issue2.code) {
        case "invalid_type":
          return `Input tidak valid: diharapkan ${issue2.expected}, diterima ${parsedType2(issue2.input)}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `Input tidak valid: diharapkan ${stringifyPrimitive(issue2.values[0])}`;
          return `Pilihan tidak valid: diharapkan salah satu dari ${joinValues(issue2.values, "|")}`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          if (sizing)
            return `Terlalu besar: diharapkan ${(_a3 = issue2.origin) != null ? _a3 : "value"} memiliki ${adj}${issue2.maximum.toString()} ${(_b2 = sizing.unit) != null ? _b2 : "elemen"}`;
          return `Terlalu besar: diharapkan ${(_c2 = issue2.origin) != null ? _c2 : "value"} menjadi ${adj}${issue2.maximum.toString()}`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `Terlalu kecil: diharapkan ${issue2.origin} memiliki ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
          }
          return `Terlalu kecil: diharapkan ${issue2.origin} menjadi ${adj}${issue2.minimum.toString()}`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with")
            return `String tidak valid: harus dimulai dengan "${_issue.prefix}"`;
          if (_issue.format === "ends_with")
            return `String tidak valid: harus berakhir dengan "${_issue.suffix}"`;
          if (_issue.format === "includes")
            return `String tidak valid: harus menyertakan "${_issue.includes}"`;
          if (_issue.format === "regex")
            return `String tidak valid: harus sesuai pola ${_issue.pattern}`;
          return `${(_d2 = Nouns[_issue.format]) != null ? _d2 : issue2.format} tidak valid`;
        }
        case "not_multiple_of":
          return `Angka tidak valid: harus kelipatan dari ${issue2.divisor}`;
        case "unrecognized_keys":
          return `Kunci tidak dikenali ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `Kunci tidak valid di ${issue2.origin}`;
        case "invalid_union":
          return "Input tidak valid";
        case "invalid_element":
          return `Nilai tidak valid di ${issue2.origin}`;
        default:
          return `Input tidak valid`;
      }
    };
  };
  function id$1() {
    return {
      localeError: error$r()
    };
  }
  const parsedType$3 = (data) => {
    const t = typeof data;
    switch (t) {
      case "number": {
        return Number.isNaN(data) ? "NaN" : "númer";
      }
      case "object": {
        if (Array.isArray(data)) {
          return "fylki";
        }
        if (data === null) {
          return "null";
        }
        if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
          return data.constructor.name;
        }
      }
    }
    return t;
  };
  const error$q = () => {
    const Sizable = {
      string: { unit: "stafi", verb: "að hafa" },
      file: { unit: "bæti", verb: "að hafa" },
      array: { unit: "hluti", verb: "að hafa" },
      set: { unit: "hluti", verb: "að hafa" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const Nouns = {
      regex: "gildi",
      email: "netfang",
      url: "vefslóð",
      emoji: "emoji",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "ISO dagsetning og tími",
      date: "ISO dagsetning",
      time: "ISO tími",
      duration: "ISO tímalengd",
      ipv4: "IPv4 address",
      ipv6: "IPv6 address",
      cidrv4: "IPv4 range",
      cidrv6: "IPv6 range",
      base64: "base64-encoded strengur",
      base64url: "base64url-encoded strengur",
      json_string: "JSON strengur",
      e164: "E.164 tölugildi",
      jwt: "JWT",
      template_literal: "gildi"
    };
    return (issue2) => {
      var _a3, _b2, _c2, _d2;
      switch (issue2.code) {
        case "invalid_type":
          return `Rangt gildi: Þú slóst inn ${parsedType$3(issue2.input)} þar sem á að vera ${issue2.expected}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `Rangt gildi: gert ráð fyrir ${stringifyPrimitive(issue2.values[0])}`;
          return `Ógilt val: má vera eitt af eftirfarandi ${joinValues(issue2.values, "|")}`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          if (sizing)
            return `Of stórt: gert er ráð fyrir að ${(_a3 = issue2.origin) != null ? _a3 : "gildi"} hafi ${adj}${issue2.maximum.toString()} ${(_b2 = sizing.unit) != null ? _b2 : "hluti"}`;
          return `Of stórt: gert er ráð fyrir að ${(_c2 = issue2.origin) != null ? _c2 : "gildi"} sé ${adj}${issue2.maximum.toString()}`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `Of lítið: gert er ráð fyrir að ${issue2.origin} hafi ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
          }
          return `Of lítið: gert er ráð fyrir að ${issue2.origin} sé ${adj}${issue2.minimum.toString()}`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with") {
            return `Ógildur strengur: verður að byrja á "${_issue.prefix}"`;
          }
          if (_issue.format === "ends_with")
            return `Ógildur strengur: verður að enda á "${_issue.suffix}"`;
          if (_issue.format === "includes")
            return `Ógildur strengur: verður að innihalda "${_issue.includes}"`;
          if (_issue.format === "regex")
            return `Ógildur strengur: verður að fylgja mynstri ${_issue.pattern}`;
          return `Rangt ${(_d2 = Nouns[_issue.format]) != null ? _d2 : issue2.format}`;
        }
        case "not_multiple_of":
          return `Röng tala: verður að vera margfeldi af ${issue2.divisor}`;
        case "unrecognized_keys":
          return `Óþekkt ${issue2.keys.length > 1 ? "ir lyklar" : "ur lykill"}: ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `Rangur lykill í ${issue2.origin}`;
        case "invalid_union":
          return "Rangt gildi";
        case "invalid_element":
          return `Rangt gildi í ${issue2.origin}`;
        default:
          return `Rangt gildi`;
      }
    };
  };
  function is() {
    return {
      localeError: error$q()
    };
  }
  const error$p = () => {
    const Sizable = {
      string: { unit: "caratteri", verb: "avere" },
      file: { unit: "byte", verb: "avere" },
      array: { unit: "elementi", verb: "avere" },
      set: { unit: "elementi", verb: "avere" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "numero";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "vettore";
          }
          if (data === null) {
            return "null";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    const Nouns = {
      regex: "input",
      email: "indirizzo email",
      url: "URL",
      emoji: "emoji",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "data e ora ISO",
      date: "data ISO",
      time: "ora ISO",
      duration: "durata ISO",
      ipv4: "indirizzo IPv4",
      ipv6: "indirizzo IPv6",
      cidrv4: "intervallo IPv4",
      cidrv6: "intervallo IPv6",
      base64: "stringa codificata in base64",
      base64url: "URL codificata in base64",
      json_string: "stringa JSON",
      e164: "numero E.164",
      jwt: "JWT",
      template_literal: "input"
    };
    return (issue2) => {
      var _a3, _b2, _c2, _d2;
      switch (issue2.code) {
        case "invalid_type":
          return `Input non valido: atteso ${issue2.expected}, ricevuto ${parsedType2(issue2.input)}`;
        // return `Input non valido: atteso ${issue.expected}, ricevuto ${util.getParsedType(issue.input)}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `Input non valido: atteso ${stringifyPrimitive(issue2.values[0])}`;
          return `Opzione non valida: atteso uno tra ${joinValues(issue2.values, "|")}`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          if (sizing)
            return `Troppo grande: ${(_a3 = issue2.origin) != null ? _a3 : "valore"} deve avere ${adj}${issue2.maximum.toString()} ${(_b2 = sizing.unit) != null ? _b2 : "elementi"}`;
          return `Troppo grande: ${(_c2 = issue2.origin) != null ? _c2 : "valore"} deve essere ${adj}${issue2.maximum.toString()}`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `Troppo piccolo: ${issue2.origin} deve avere ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
          }
          return `Troppo piccolo: ${issue2.origin} deve essere ${adj}${issue2.minimum.toString()}`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with")
            return `Stringa non valida: deve iniziare con "${_issue.prefix}"`;
          if (_issue.format === "ends_with")
            return `Stringa non valida: deve terminare con "${_issue.suffix}"`;
          if (_issue.format === "includes")
            return `Stringa non valida: deve includere "${_issue.includes}"`;
          if (_issue.format === "regex")
            return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`;
          return `Invalid ${(_d2 = Nouns[_issue.format]) != null ? _d2 : issue2.format}`;
        }
        case "not_multiple_of":
          return `Numero non valido: deve essere un multiplo di ${issue2.divisor}`;
        case "unrecognized_keys":
          return `Chiav${issue2.keys.length > 1 ? "i" : "e"} non riconosciut${issue2.keys.length > 1 ? "e" : "a"}: ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `Chiave non valida in ${issue2.origin}`;
        case "invalid_union":
          return "Input non valido";
        case "invalid_element":
          return `Valore non valido in ${issue2.origin}`;
        default:
          return `Input non valido`;
      }
    };
  };
  function it() {
    return {
      localeError: error$p()
    };
  }
  const error$o = () => {
    const Sizable = {
      string: { unit: "文字", verb: "である" },
      file: { unit: "バイト", verb: "である" },
      array: { unit: "要素", verb: "である" },
      set: { unit: "要素", verb: "である" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "数値";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "配列";
          }
          if (data === null) {
            return "null";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    const Nouns = {
      regex: "入力値",
      email: "メールアドレス",
      url: "URL",
      emoji: "絵文字",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "ISO日時",
      date: "ISO日付",
      time: "ISO時刻",
      duration: "ISO期間",
      ipv4: "IPv4アドレス",
      ipv6: "IPv6アドレス",
      cidrv4: "IPv4範囲",
      cidrv6: "IPv6範囲",
      base64: "base64エンコード文字列",
      base64url: "base64urlエンコード文字列",
      json_string: "JSON文字列",
      e164: "E.164番号",
      jwt: "JWT",
      template_literal: "入力値"
    };
    return (issue2) => {
      var _a3, _b2, _c2, _d2;
      switch (issue2.code) {
        case "invalid_type":
          return `無効な入力: ${issue2.expected}が期待されましたが、${parsedType2(issue2.input)}が入力されました`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `無効な入力: ${stringifyPrimitive(issue2.values[0])}が期待されました`;
          return `無効な選択: ${joinValues(issue2.values, "、")}のいずれかである必要があります`;
        case "too_big": {
          const adj = issue2.inclusive ? "以下である" : "より小さい";
          const sizing = getSizing(issue2.origin);
          if (sizing)
            return `大きすぎる値: ${(_a3 = issue2.origin) != null ? _a3 : "値"}は${issue2.maximum.toString()}${(_b2 = sizing.unit) != null ? _b2 : "要素"}${adj}必要があります`;
          return `大きすぎる値: ${(_c2 = issue2.origin) != null ? _c2 : "値"}は${issue2.maximum.toString()}${adj}必要があります`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? "以上である" : "より大きい";
          const sizing = getSizing(issue2.origin);
          if (sizing)
            return `小さすぎる値: ${issue2.origin}は${issue2.minimum.toString()}${sizing.unit}${adj}必要があります`;
          return `小さすぎる値: ${issue2.origin}は${issue2.minimum.toString()}${adj}必要があります`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with")
            return `無効な文字列: "${_issue.prefix}"で始まる必要があります`;
          if (_issue.format === "ends_with")
            return `無効な文字列: "${_issue.suffix}"で終わる必要があります`;
          if (_issue.format === "includes")
            return `無効な文字列: "${_issue.includes}"を含む必要があります`;
          if (_issue.format === "regex")
            return `無効な文字列: パターン${_issue.pattern}に一致する必要があります`;
          return `無効な${(_d2 = Nouns[_issue.format]) != null ? _d2 : issue2.format}`;
        }
        case "not_multiple_of":
          return `無効な数値: ${issue2.divisor}の倍数である必要があります`;
        case "unrecognized_keys":
          return `認識されていないキー${issue2.keys.length > 1 ? "群" : ""}: ${joinValues(issue2.keys, "、")}`;
        case "invalid_key":
          return `${issue2.origin}内の無効なキー`;
        case "invalid_union":
          return "無効な入力";
        case "invalid_element":
          return `${issue2.origin}内の無効な値`;
        default:
          return `無効な入力`;
      }
    };
  };
  function ja() {
    return {
      localeError: error$o()
    };
  }
  const parsedType$2 = (data) => {
    var _a3;
    const t = typeof data;
    switch (t) {
      case "number": {
        return Number.isNaN(data) ? "NaN" : "რიცხვი";
      }
      case "object": {
        if (Array.isArray(data)) {
          return "მასივი";
        }
        if (data === null) {
          return "null";
        }
        if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
          return data.constructor.name;
        }
      }
    }
    const typeMap = {
      string: "სტრინგი",
      boolean: "ბულეანი",
      undefined: "undefined",
      bigint: "bigint",
      symbol: "symbol",
      function: "ფუნქცია"
    };
    return (_a3 = typeMap[t]) != null ? _a3 : t;
  };
  const error$n = () => {
    const Sizable = {
      string: { unit: "სიმბოლო", verb: "უნდა შეიცავდეს" },
      file: { unit: "ბაიტი", verb: "უნდა შეიცავდეს" },
      array: { unit: "ელემენტი", verb: "უნდა შეიცავდეს" },
      set: { unit: "ელემენტი", verb: "უნდა შეიცავდეს" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const Nouns = {
      regex: "შეყვანა",
      email: "ელ-ფოსტის მისამართი",
      url: "URL",
      emoji: "ემოჯი",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "თარიღი-დრო",
      date: "თარიღი",
      time: "დრო",
      duration: "ხანგრძლივობა",
      ipv4: "IPv4 მისამართი",
      ipv6: "IPv6 მისამართი",
      cidrv4: "IPv4 დიაპაზონი",
      cidrv6: "IPv6 დიაპაზონი",
      base64: "base64-კოდირებული სტრინგი",
      base64url: "base64url-კოდირებული სტრინგი",
      json_string: "JSON სტრინგი",
      e164: "E.164 ნომერი",
      jwt: "JWT",
      template_literal: "შეყვანა"
    };
    return (issue2) => {
      var _a3, _b2, _c2;
      switch (issue2.code) {
        case "invalid_type":
          return `არასწორი შეყვანა: მოსალოდნელი ${issue2.expected}, მიღებული ${parsedType$2(issue2.input)}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `არასწორი შეყვანა: მოსალოდნელი ${stringifyPrimitive(issue2.values[0])}`;
          return `არასწორი ვარიანტი: მოსალოდნელია ერთ-ერთი ${joinValues(issue2.values, "|")}-დან`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          if (sizing)
            return `ზედმეტად დიდი: მოსალოდნელი ${(_a3 = issue2.origin) != null ? _a3 : "მნიშვნელობა"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit}`;
          return `ზედმეტად დიდი: მოსალოდნელი ${(_b2 = issue2.origin) != null ? _b2 : "მნიშვნელობა"} იყოს ${adj}${issue2.maximum.toString()}`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `ზედმეტად პატარა: მოსალოდნელი ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
          }
          return `ზედმეტად პატარა: მოსალოდნელი ${issue2.origin} იყოს ${adj}${issue2.minimum.toString()}`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with") {
            return `არასწორი სტრინგი: უნდა იწყებოდეს "${_issue.prefix}"-ით`;
          }
          if (_issue.format === "ends_with")
            return `არასწორი სტრინგი: უნდა მთავრდებოდეს "${_issue.suffix}"-ით`;
          if (_issue.format === "includes")
            return `არასწორი სტრინგი: უნდა შეიცავდეს "${_issue.includes}"-ს`;
          if (_issue.format === "regex")
            return `არასწორი სტრინგი: უნდა შეესაბამებოდეს შაბლონს ${_issue.pattern}`;
          return `არასწორი ${(_c2 = Nouns[_issue.format]) != null ? _c2 : issue2.format}`;
        }
        case "not_multiple_of":
          return `არასწორი რიცხვი: უნდა იყოს ${issue2.divisor}-ის ჯერადი`;
        case "unrecognized_keys":
          return `უცნობი გასაღებ${issue2.keys.length > 1 ? "ები" : "ი"}: ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `არასწორი გასაღები ${issue2.origin}-ში`;
        case "invalid_union":
          return "არასწორი შეყვანა";
        case "invalid_element":
          return `არასწორი მნიშვნელობა ${issue2.origin}-ში`;
        default:
          return `არასწორი შეყვანა`;
      }
    };
  };
  function ka() {
    return {
      localeError: error$n()
    };
  }
  const error$m = () => {
    const Sizable = {
      string: { unit: "តួអក្សរ", verb: "គួរមាន" },
      file: { unit: "បៃ", verb: "គួរមាន" },
      array: { unit: "ធាតុ", verb: "គួរមាន" },
      set: { unit: "ធាតុ", verb: "គួរមាន" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "មិនមែនជាលេខ (NaN)" : "លេខ";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "អារេ (Array)";
          }
          if (data === null) {
            return "គ្មានតម្លៃ (null)";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    const Nouns = {
      regex: "ទិន្នន័យបញ្ចូល",
      email: "អាសយដ្ឋានអ៊ីមែល",
      url: "URL",
      emoji: "សញ្ញាអារម្មណ៍",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "កាលបរិច្ឆេទ និងម៉ោង ISO",
      date: "កាលបរិច្ឆេទ ISO",
      time: "ម៉ោង ISO",
      duration: "រយៈពេល ISO",
      ipv4: "អាសយដ្ឋាន IPv4",
      ipv6: "អាសយដ្ឋាន IPv6",
      cidrv4: "ដែនអាសយដ្ឋាន IPv4",
      cidrv6: "ដែនអាសយដ្ឋាន IPv6",
      base64: "ខ្សែអក្សរអ៊ិកូដ base64",
      base64url: "ខ្សែអក្សរអ៊ិកូដ base64url",
      json_string: "ខ្សែអក្សរ JSON",
      e164: "លេខ E.164",
      jwt: "JWT",
      template_literal: "ទិន្នន័យបញ្ចូល"
    };
    return (issue2) => {
      var _a3, _b2, _c2, _d2;
      switch (issue2.code) {
        case "invalid_type":
          return `ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${issue2.expected} ប៉ុន្តែទទួលបាន ${parsedType2(issue2.input)}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${stringifyPrimitive(issue2.values[0])}`;
          return `ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${joinValues(issue2.values, "|")}`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          if (sizing)
            return `ធំពេក៖ ត្រូវការ ${(_a3 = issue2.origin) != null ? _a3 : "តម្លៃ"} ${adj} ${issue2.maximum.toString()} ${(_b2 = sizing.unit) != null ? _b2 : "ធាតុ"}`;
          return `ធំពេក៖ ត្រូវការ ${(_c2 = issue2.origin) != null ? _c2 : "តម្លៃ"} ${adj} ${issue2.maximum.toString()}`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `តូចពេក៖ ត្រូវការ ${issue2.origin} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
          }
          return `តូចពេក៖ ត្រូវការ ${issue2.origin} ${adj} ${issue2.minimum.toString()}`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with") {
            return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${_issue.prefix}"`;
          }
          if (_issue.format === "ends_with")
            return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${_issue.suffix}"`;
          if (_issue.format === "includes")
            return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${_issue.includes}"`;
          if (_issue.format === "regex")
            return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${_issue.pattern}`;
          return `មិនត្រឹមត្រូវ៖ ${(_d2 = Nouns[_issue.format]) != null ? _d2 : issue2.format}`;
        }
        case "not_multiple_of":
          return `លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${issue2.divisor}`;
        case "unrecognized_keys":
          return `រកឃើញសោមិនស្គាល់៖ ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `សោមិនត្រឹមត្រូវនៅក្នុង ${issue2.origin}`;
        case "invalid_union":
          return `ទិន្នន័យមិនត្រឹមត្រូវ`;
        case "invalid_element":
          return `ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${issue2.origin}`;
        default:
          return `ទិន្នន័យមិនត្រឹមត្រូវ`;
      }
    };
  };
  function km() {
    return {
      localeError: error$m()
    };
  }
  function kh() {
    return km();
  }
  const error$l = () => {
    const Sizable = {
      string: { unit: "문자", verb: "to have" },
      file: { unit: "바이트", verb: "to have" },
      array: { unit: "개", verb: "to have" },
      set: { unit: "개", verb: "to have" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "number";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "array";
          }
          if (data === null) {
            return "null";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    const Nouns = {
      regex: "입력",
      email: "이메일 주소",
      url: "URL",
      emoji: "이모지",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "ISO 날짜시간",
      date: "ISO 날짜",
      time: "ISO 시간",
      duration: "ISO 기간",
      ipv4: "IPv4 주소",
      ipv6: "IPv6 주소",
      cidrv4: "IPv4 범위",
      cidrv6: "IPv6 범위",
      base64: "base64 인코딩 문자열",
      base64url: "base64url 인코딩 문자열",
      json_string: "JSON 문자열",
      e164: "E.164 번호",
      jwt: "JWT",
      template_literal: "입력"
    };
    return (issue2) => {
      var _a3, _b2, _c2, _d2, _e, _f, _g;
      switch (issue2.code) {
        case "invalid_type":
          return `잘못된 입력: 예상 타입은 ${issue2.expected}, 받은 타입은 ${parsedType2(issue2.input)}입니다`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `잘못된 입력: 값은 ${stringifyPrimitive(issue2.values[0])} 이어야 합니다`;
          return `잘못된 옵션: ${joinValues(issue2.values, "또는 ")} 중 하나여야 합니다`;
        case "too_big": {
          const adj = issue2.inclusive ? "이하" : "미만";
          const suffix = adj === "미만" ? "이어야 합니다" : "여야 합니다";
          const sizing = getSizing(issue2.origin);
          const unit = (_a3 = sizing == null ? void 0 : sizing.unit) != null ? _a3 : "요소";
          if (sizing)
            return `${(_b2 = issue2.origin) != null ? _b2 : "값"}이 너무 큽니다: ${issue2.maximum.toString()}${unit} ${adj}${suffix}`;
          return `${(_c2 = issue2.origin) != null ? _c2 : "값"}이 너무 큽니다: ${issue2.maximum.toString()} ${adj}${suffix}`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? "이상" : "초과";
          const suffix = adj === "이상" ? "이어야 합니다" : "여야 합니다";
          const sizing = getSizing(issue2.origin);
          const unit = (_d2 = sizing == null ? void 0 : sizing.unit) != null ? _d2 : "요소";
          if (sizing) {
            return `${(_e = issue2.origin) != null ? _e : "값"}이 너무 작습니다: ${issue2.minimum.toString()}${unit} ${adj}${suffix}`;
          }
          return `${(_f = issue2.origin) != null ? _f : "값"}이 너무 작습니다: ${issue2.minimum.toString()} ${adj}${suffix}`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with") {
            return `잘못된 문자열: "${_issue.prefix}"(으)로 시작해야 합니다`;
          }
          if (_issue.format === "ends_with")
            return `잘못된 문자열: "${_issue.suffix}"(으)로 끝나야 합니다`;
          if (_issue.format === "includes")
            return `잘못된 문자열: "${_issue.includes}"을(를) 포함해야 합니다`;
          if (_issue.format === "regex")
            return `잘못된 문자열: 정규식 ${_issue.pattern} 패턴과 일치해야 합니다`;
          return `잘못된 ${(_g = Nouns[_issue.format]) != null ? _g : issue2.format}`;
        }
        case "not_multiple_of":
          return `잘못된 숫자: ${issue2.divisor}의 배수여야 합니다`;
        case "unrecognized_keys":
          return `인식할 수 없는 키: ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `잘못된 키: ${issue2.origin}`;
        case "invalid_union":
          return `잘못된 입력`;
        case "invalid_element":
          return `잘못된 값: ${issue2.origin}`;
        default:
          return `잘못된 입력`;
      }
    };
  };
  function ko() {
    return {
      localeError: error$l()
    };
  }
  const parsedType$1 = (data) => {
    const t = typeof data;
    return parsedTypeFromType(t, data);
  };
  const parsedTypeFromType = (t, data = void 0) => {
    switch (t) {
      case "number": {
        return Number.isNaN(data) ? "NaN" : "skaičius";
      }
      case "bigint": {
        return "sveikasis skaičius";
      }
      case "string": {
        return "eilutė";
      }
      case "boolean": {
        return "loginė reikšmė";
      }
      case "undefined":
      case "void": {
        return "neapibrėžta reikšmė";
      }
      case "function": {
        return "funkcija";
      }
      case "symbol": {
        return "simbolis";
      }
      case "object": {
        if (data === void 0)
          return "nežinomas objektas";
        if (data === null)
          return "nulinė reikšmė";
        if (Array.isArray(data))
          return "masyvas";
        if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
          return data.constructor.name;
        }
        return "objektas";
      }
      //Zod types below
      case "null": {
        return "nulinė reikšmė";
      }
    }
    return t;
  };
  const capitalizeFirstCharacter = (text) => {
    return text.charAt(0).toUpperCase() + text.slice(1);
  };
  function getUnitTypeFromNumber(number2) {
    const abs = Math.abs(number2);
    const last = abs % 10;
    const last2 = abs % 100;
    if (last2 >= 11 && last2 <= 19 || last === 0)
      return "many";
    if (last === 1)
      return "one";
    return "few";
  }
  const error$k = () => {
    const Sizable = {
      string: {
        unit: {
          one: "simbolis",
          few: "simboliai",
          many: "simbolių"
        },
        verb: {
          smaller: {
            inclusive: "turi būti ne ilgesnė kaip",
            notInclusive: "turi būti trumpesnė kaip"
          },
          bigger: {
            inclusive: "turi būti ne trumpesnė kaip",
            notInclusive: "turi būti ilgesnė kaip"
          }
        }
      },
      file: {
        unit: {
          one: "baitas",
          few: "baitai",
          many: "baitų"
        },
        verb: {
          smaller: {
            inclusive: "turi būti ne didesnis kaip",
            notInclusive: "turi būti mažesnis kaip"
          },
          bigger: {
            inclusive: "turi būti ne mažesnis kaip",
            notInclusive: "turi būti didesnis kaip"
          }
        }
      },
      array: {
        unit: {
          one: "elementą",
          few: "elementus",
          many: "elementų"
        },
        verb: {
          smaller: {
            inclusive: "turi turėti ne daugiau kaip",
            notInclusive: "turi turėti mažiau kaip"
          },
          bigger: {
            inclusive: "turi turėti ne mažiau kaip",
            notInclusive: "turi turėti daugiau kaip"
          }
        }
      },
      set: {
        unit: {
          one: "elementą",
          few: "elementus",
          many: "elementų"
        },
        verb: {
          smaller: {
            inclusive: "turi turėti ne daugiau kaip",
            notInclusive: "turi turėti mažiau kaip"
          },
          bigger: {
            inclusive: "turi turėti ne mažiau kaip",
            notInclusive: "turi turėti daugiau kaip"
          }
        }
      }
    };
    function getSizing(origin, unitType, inclusive, targetShouldBe) {
      var _a3;
      const result2 = (_a3 = Sizable[origin]) != null ? _a3 : null;
      if (result2 === null)
        return result2;
      return {
        unit: result2.unit[unitType],
        verb: result2.verb[targetShouldBe][inclusive ? "inclusive" : "notInclusive"]
      };
    }
    const Nouns = {
      regex: "įvestis",
      email: "el. pašto adresas",
      url: "URL",
      emoji: "jaustukas",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "ISO data ir laikas",
      date: "ISO data",
      time: "ISO laikas",
      duration: "ISO trukmė",
      ipv4: "IPv4 adresas",
      ipv6: "IPv6 adresas",
      cidrv4: "IPv4 tinklo prefiksas (CIDR)",
      cidrv6: "IPv6 tinklo prefiksas (CIDR)",
      base64: "base64 užkoduota eilutė",
      base64url: "base64url užkoduota eilutė",
      json_string: "JSON eilutė",
      e164: "E.164 numeris",
      jwt: "JWT",
      template_literal: "įvestis"
    };
    return (issue2) => {
      var _a3, _b2, _c2, _d2, _e, _f, _g, _h, _i, _j;
      switch (issue2.code) {
        case "invalid_type":
          return `Gautas tipas ${parsedType$1(issue2.input)}, o tikėtasi - ${parsedTypeFromType(issue2.expected)}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `Privalo būti ${stringifyPrimitive(issue2.values[0])}`;
          return `Privalo būti vienas iš ${joinValues(issue2.values, "|")} pasirinkimų`;
        case "too_big": {
          const origin = parsedTypeFromType(issue2.origin);
          const sizing = getSizing(issue2.origin, getUnitTypeFromNumber(Number(issue2.maximum)), (_a3 = issue2.inclusive) != null ? _a3 : false, "smaller");
          if (sizing == null ? void 0 : sizing.verb)
            return `${capitalizeFirstCharacter((_b2 = origin != null ? origin : issue2.origin) != null ? _b2 : "reikšmė")} ${sizing.verb} ${issue2.maximum.toString()} ${(_c2 = sizing.unit) != null ? _c2 : "elementų"}`;
          const adj = issue2.inclusive ? "ne didesnis kaip" : "mažesnis kaip";
          return `${capitalizeFirstCharacter((_d2 = origin != null ? origin : issue2.origin) != null ? _d2 : "reikšmė")} turi būti ${adj} ${issue2.maximum.toString()} ${sizing == null ? void 0 : sizing.unit}`;
        }
        case "too_small": {
          const origin = parsedTypeFromType(issue2.origin);
          const sizing = getSizing(issue2.origin, getUnitTypeFromNumber(Number(issue2.minimum)), (_e = issue2.inclusive) != null ? _e : false, "bigger");
          if (sizing == null ? void 0 : sizing.verb)
            return `${capitalizeFirstCharacter((_f = origin != null ? origin : issue2.origin) != null ? _f : "reikšmė")} ${sizing.verb} ${issue2.minimum.toString()} ${(_g = sizing.unit) != null ? _g : "elementų"}`;
          const adj = issue2.inclusive ? "ne mažesnis kaip" : "didesnis kaip";
          return `${capitalizeFirstCharacter((_h = origin != null ? origin : issue2.origin) != null ? _h : "reikšmė")} turi būti ${adj} ${issue2.minimum.toString()} ${sizing == null ? void 0 : sizing.unit}`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with") {
            return `Eilutė privalo prasidėti "${_issue.prefix}"`;
          }
          if (_issue.format === "ends_with")
            return `Eilutė privalo pasibaigti "${_issue.suffix}"`;
          if (_issue.format === "includes")
            return `Eilutė privalo įtraukti "${_issue.includes}"`;
          if (_issue.format === "regex")
            return `Eilutė privalo atitikti ${_issue.pattern}`;
          return `Neteisingas ${(_i = Nouns[_issue.format]) != null ? _i : issue2.format}`;
        }
        case "not_multiple_of":
          return `Skaičius privalo būti ${issue2.divisor} kartotinis.`;
        case "unrecognized_keys":
          return `Neatpažint${issue2.keys.length > 1 ? "i" : "as"} rakt${issue2.keys.length > 1 ? "ai" : "as"}: ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return "Rastas klaidingas raktas";
        case "invalid_union":
          return "Klaidinga įvestis";
        case "invalid_element": {
          const origin = parsedTypeFromType(issue2.origin);
          return `${capitalizeFirstCharacter((_j = origin != null ? origin : issue2.origin) != null ? _j : "reikšmė")} turi klaidingą įvestį`;
        }
        default:
          return "Klaidinga įvestis";
      }
    };
  };
  function lt() {
    return {
      localeError: error$k()
    };
  }
  const error$j = () => {
    const Sizable = {
      string: { unit: "знаци", verb: "да имаат" },
      file: { unit: "бајти", verb: "да имаат" },
      array: { unit: "ставки", verb: "да имаат" },
      set: { unit: "ставки", verb: "да имаат" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "број";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "низа";
          }
          if (data === null) {
            return "null";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    const Nouns = {
      regex: "внес",
      email: "адреса на е-пошта",
      url: "URL",
      emoji: "емоџи",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "ISO датум и време",
      date: "ISO датум",
      time: "ISO време",
      duration: "ISO времетраење",
      ipv4: "IPv4 адреса",
      ipv6: "IPv6 адреса",
      cidrv4: "IPv4 опсег",
      cidrv6: "IPv6 опсег",
      base64: "base64-енкодирана низа",
      base64url: "base64url-енкодирана низа",
      json_string: "JSON низа",
      e164: "E.164 број",
      jwt: "JWT",
      template_literal: "внес"
    };
    return (issue2) => {
      var _a3, _b2, _c2, _d2;
      switch (issue2.code) {
        case "invalid_type":
          return `Грешен внес: се очекува ${issue2.expected}, примено ${parsedType2(issue2.input)}`;
        // return `Invalid input: expected ${issue.expected}, received ${util.getParsedType(issue.input)}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`;
          return `Грешана опција: се очекува една ${joinValues(issue2.values, "|")}`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          if (sizing)
            return `Премногу голем: се очекува ${(_a3 = issue2.origin) != null ? _a3 : "вредноста"} да има ${adj}${issue2.maximum.toString()} ${(_b2 = sizing.unit) != null ? _b2 : "елементи"}`;
          return `Премногу голем: се очекува ${(_c2 = issue2.origin) != null ? _c2 : "вредноста"} да биде ${adj}${issue2.maximum.toString()}`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `Премногу мал: се очекува ${issue2.origin} да има ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
          }
          return `Премногу мал: се очекува ${issue2.origin} да биде ${adj}${issue2.minimum.toString()}`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with") {
            return `Неважечка низа: мора да започнува со "${_issue.prefix}"`;
          }
          if (_issue.format === "ends_with")
            return `Неважечка низа: мора да завршува со "${_issue.suffix}"`;
          if (_issue.format === "includes")
            return `Неважечка низа: мора да вклучува "${_issue.includes}"`;
          if (_issue.format === "regex")
            return `Неважечка низа: мора да одгоара на патернот ${_issue.pattern}`;
          return `Invalid ${(_d2 = Nouns[_issue.format]) != null ? _d2 : issue2.format}`;
        }
        case "not_multiple_of":
          return `Грешен број: мора да биде делив со ${issue2.divisor}`;
        case "unrecognized_keys":
          return `${issue2.keys.length > 1 ? "Непрепознаени клучеви" : "Непрепознаен клуч"}: ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `Грешен клуч во ${issue2.origin}`;
        case "invalid_union":
          return "Грешен внес";
        case "invalid_element":
          return `Грешна вредност во ${issue2.origin}`;
        default:
          return `Грешен внес`;
      }
    };
  };
  function mk() {
    return {
      localeError: error$j()
    };
  }
  const error$i = () => {
    const Sizable = {
      string: { unit: "aksara", verb: "mempunyai" },
      file: { unit: "bait", verb: "mempunyai" },
      array: { unit: "elemen", verb: "mempunyai" },
      set: { unit: "elemen", verb: "mempunyai" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "nombor";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "array";
          }
          if (data === null) {
            return "null";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    const Nouns = {
      regex: "input",
      email: "alamat e-mel",
      url: "URL",
      emoji: "emoji",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "tarikh masa ISO",
      date: "tarikh ISO",
      time: "masa ISO",
      duration: "tempoh ISO",
      ipv4: "alamat IPv4",
      ipv6: "alamat IPv6",
      cidrv4: "julat IPv4",
      cidrv6: "julat IPv6",
      base64: "string dikodkan base64",
      base64url: "string dikodkan base64url",
      json_string: "string JSON",
      e164: "nombor E.164",
      jwt: "JWT",
      template_literal: "input"
    };
    return (issue2) => {
      var _a3, _b2, _c2, _d2;
      switch (issue2.code) {
        case "invalid_type":
          return `Input tidak sah: dijangka ${issue2.expected}, diterima ${parsedType2(issue2.input)}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `Input tidak sah: dijangka ${stringifyPrimitive(issue2.values[0])}`;
          return `Pilihan tidak sah: dijangka salah satu daripada ${joinValues(issue2.values, "|")}`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          if (sizing)
            return `Terlalu besar: dijangka ${(_a3 = issue2.origin) != null ? _a3 : "nilai"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${(_b2 = sizing.unit) != null ? _b2 : "elemen"}`;
          return `Terlalu besar: dijangka ${(_c2 = issue2.origin) != null ? _c2 : "nilai"} adalah ${adj}${issue2.maximum.toString()}`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `Terlalu kecil: dijangka ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
          }
          return `Terlalu kecil: dijangka ${issue2.origin} adalah ${adj}${issue2.minimum.toString()}`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with")
            return `String tidak sah: mesti bermula dengan "${_issue.prefix}"`;
          if (_issue.format === "ends_with")
            return `String tidak sah: mesti berakhir dengan "${_issue.suffix}"`;
          if (_issue.format === "includes")
            return `String tidak sah: mesti mengandungi "${_issue.includes}"`;
          if (_issue.format === "regex")
            return `String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`;
          return `${(_d2 = Nouns[_issue.format]) != null ? _d2 : issue2.format} tidak sah`;
        }
        case "not_multiple_of":
          return `Nombor tidak sah: perlu gandaan ${issue2.divisor}`;
        case "unrecognized_keys":
          return `Kunci tidak dikenali: ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `Kunci tidak sah dalam ${issue2.origin}`;
        case "invalid_union":
          return "Input tidak sah";
        case "invalid_element":
          return `Nilai tidak sah dalam ${issue2.origin}`;
        default:
          return `Input tidak sah`;
      }
    };
  };
  function ms() {
    return {
      localeError: error$i()
    };
  }
  const error$h = () => {
    const Sizable = {
      string: { unit: "tekens", verb: "te hebben" },
      file: { unit: "bytes", verb: "te hebben" },
      array: { unit: "elementen", verb: "te hebben" },
      set: { unit: "elementen", verb: "te hebben" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "getal";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "array";
          }
          if (data === null) {
            return "null";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    const Nouns = {
      regex: "invoer",
      email: "emailadres",
      url: "URL",
      emoji: "emoji",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "ISO datum en tijd",
      date: "ISO datum",
      time: "ISO tijd",
      duration: "ISO duur",
      ipv4: "IPv4-adres",
      ipv6: "IPv6-adres",
      cidrv4: "IPv4-bereik",
      cidrv6: "IPv6-bereik",
      base64: "base64-gecodeerde tekst",
      base64url: "base64 URL-gecodeerde tekst",
      json_string: "JSON string",
      e164: "E.164-nummer",
      jwt: "JWT",
      template_literal: "invoer"
    };
    return (issue2) => {
      var _a3, _b2, _c2, _d2;
      switch (issue2.code) {
        case "invalid_type":
          return `Ongeldige invoer: verwacht ${issue2.expected}, ontving ${parsedType2(issue2.input)}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `Ongeldige invoer: verwacht ${stringifyPrimitive(issue2.values[0])}`;
          return `Ongeldige optie: verwacht één van ${joinValues(issue2.values, "|")}`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          if (sizing)
            return `Te groot: verwacht dat ${(_a3 = issue2.origin) != null ? _a3 : "waarde"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${(_b2 = sizing.unit) != null ? _b2 : "elementen"}`;
          return `Te groot: verwacht dat ${(_c2 = issue2.origin) != null ? _c2 : "waarde"} ${adj}${issue2.maximum.toString()} is`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `Te klein: verwacht dat ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
          }
          return `Te klein: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} is`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with") {
            return `Ongeldige tekst: moet met "${_issue.prefix}" beginnen`;
          }
          if (_issue.format === "ends_with")
            return `Ongeldige tekst: moet op "${_issue.suffix}" eindigen`;
          if (_issue.format === "includes")
            return `Ongeldige tekst: moet "${_issue.includes}" bevatten`;
          if (_issue.format === "regex")
            return `Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`;
          return `Ongeldig: ${(_d2 = Nouns[_issue.format]) != null ? _d2 : issue2.format}`;
        }
        case "not_multiple_of":
          return `Ongeldig getal: moet een veelvoud van ${issue2.divisor} zijn`;
        case "unrecognized_keys":
          return `Onbekende key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `Ongeldige key in ${issue2.origin}`;
        case "invalid_union":
          return "Ongeldige invoer";
        case "invalid_element":
          return `Ongeldige waarde in ${issue2.origin}`;
        default:
          return `Ongeldige invoer`;
      }
    };
  };
  function nl() {
    return {
      localeError: error$h()
    };
  }
  const error$g = () => {
    const Sizable = {
      string: { unit: "tegn", verb: "å ha" },
      file: { unit: "bytes", verb: "å ha" },
      array: { unit: "elementer", verb: "å inneholde" },
      set: { unit: "elementer", verb: "å inneholde" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "tall";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "liste";
          }
          if (data === null) {
            return "null";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    const Nouns = {
      regex: "input",
      email: "e-postadresse",
      url: "URL",
      emoji: "emoji",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "ISO dato- og klokkeslett",
      date: "ISO-dato",
      time: "ISO-klokkeslett",
      duration: "ISO-varighet",
      ipv4: "IPv4-område",
      ipv6: "IPv6-område",
      cidrv4: "IPv4-spekter",
      cidrv6: "IPv6-spekter",
      base64: "base64-enkodet streng",
      base64url: "base64url-enkodet streng",
      json_string: "JSON-streng",
      e164: "E.164-nummer",
      jwt: "JWT",
      template_literal: "input"
    };
    return (issue2) => {
      var _a3, _b2, _c2, _d2;
      switch (issue2.code) {
        case "invalid_type":
          return `Ugyldig input: forventet ${issue2.expected}, fikk ${parsedType2(issue2.input)}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `Ugyldig verdi: forventet ${stringifyPrimitive(issue2.values[0])}`;
          return `Ugyldig valg: forventet en av ${joinValues(issue2.values, "|")}`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          if (sizing)
            return `For stor(t): forventet ${(_a3 = issue2.origin) != null ? _a3 : "value"} til å ha ${adj}${issue2.maximum.toString()} ${(_b2 = sizing.unit) != null ? _b2 : "elementer"}`;
          return `For stor(t): forventet ${(_c2 = issue2.origin) != null ? _c2 : "value"} til å ha ${adj}${issue2.maximum.toString()}`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `For lite(n): forventet ${issue2.origin} til å ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
          }
          return `For lite(n): forventet ${issue2.origin} til å ha ${adj}${issue2.minimum.toString()}`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with")
            return `Ugyldig streng: må starte med "${_issue.prefix}"`;
          if (_issue.format === "ends_with")
            return `Ugyldig streng: må ende med "${_issue.suffix}"`;
          if (_issue.format === "includes")
            return `Ugyldig streng: må inneholde "${_issue.includes}"`;
          if (_issue.format === "regex")
            return `Ugyldig streng: må matche mønsteret ${_issue.pattern}`;
          return `Ugyldig ${(_d2 = Nouns[_issue.format]) != null ? _d2 : issue2.format}`;
        }
        case "not_multiple_of":
          return `Ugyldig tall: må være et multiplum av ${issue2.divisor}`;
        case "unrecognized_keys":
          return `${issue2.keys.length > 1 ? "Ukjente nøkler" : "Ukjent nøkkel"}: ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `Ugyldig nøkkel i ${issue2.origin}`;
        case "invalid_union":
          return "Ugyldig input";
        case "invalid_element":
          return `Ugyldig verdi i ${issue2.origin}`;
        default:
          return `Ugyldig input`;
      }
    };
  };
  function no() {
    return {
      localeError: error$g()
    };
  }
  const error$f = () => {
    const Sizable = {
      string: { unit: "harf", verb: "olmalıdır" },
      file: { unit: "bayt", verb: "olmalıdır" },
      array: { unit: "unsur", verb: "olmalıdır" },
      set: { unit: "unsur", verb: "olmalıdır" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "numara";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "saf";
          }
          if (data === null) {
            return "gayb";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    const Nouns = {
      regex: "giren",
      email: "epostagâh",
      url: "URL",
      emoji: "emoji",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "ISO hengâmı",
      date: "ISO tarihi",
      time: "ISO zamanı",
      duration: "ISO müddeti",
      ipv4: "IPv4 nişânı",
      ipv6: "IPv6 nişânı",
      cidrv4: "IPv4 menzili",
      cidrv6: "IPv6 menzili",
      base64: "base64-şifreli metin",
      base64url: "base64url-şifreli metin",
      json_string: "JSON metin",
      e164: "E.164 sayısı",
      jwt: "JWT",
      template_literal: "giren"
    };
    return (issue2) => {
      var _a3, _b2, _c2, _d2;
      switch (issue2.code) {
        case "invalid_type":
          return `Fâsit giren: umulan ${issue2.expected}, alınan ${parsedType2(issue2.input)}`;
        // return `Fâsit giren: umulan ${issue.expected}, alınan ${util.getParsedType(issue.input)}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `Fâsit giren: umulan ${stringifyPrimitive(issue2.values[0])}`;
          return `Fâsit tercih: mûteberler ${joinValues(issue2.values, "|")}`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          if (sizing)
            return `Fazla büyük: ${(_a3 = issue2.origin) != null ? _a3 : "value"}, ${adj}${issue2.maximum.toString()} ${(_b2 = sizing.unit) != null ? _b2 : "elements"} sahip olmalıydı.`;
          return `Fazla büyük: ${(_c2 = issue2.origin) != null ? _c2 : "value"}, ${adj}${issue2.maximum.toString()} olmalıydı.`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `Fazla küçük: ${issue2.origin}, ${adj}${issue2.minimum.toString()} ${sizing.unit} sahip olmalıydı.`;
          }
          return `Fazla küçük: ${issue2.origin}, ${adj}${issue2.minimum.toString()} olmalıydı.`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with")
            return `Fâsit metin: "${_issue.prefix}" ile başlamalı.`;
          if (_issue.format === "ends_with")
            return `Fâsit metin: "${_issue.suffix}" ile bitmeli.`;
          if (_issue.format === "includes")
            return `Fâsit metin: "${_issue.includes}" ihtivâ etmeli.`;
          if (_issue.format === "regex")
            return `Fâsit metin: ${_issue.pattern} nakşına uymalı.`;
          return `Fâsit ${(_d2 = Nouns[_issue.format]) != null ? _d2 : issue2.format}`;
        }
        case "not_multiple_of":
          return `Fâsit sayı: ${issue2.divisor} katı olmalıydı.`;
        case "unrecognized_keys":
          return `Tanınmayan anahtar ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `${issue2.origin} için tanınmayan anahtar var.`;
        case "invalid_union":
          return "Giren tanınamadı.";
        case "invalid_element":
          return `${issue2.origin} için tanınmayan kıymet var.`;
        default:
          return `Kıymet tanınamadı.`;
      }
    };
  };
  function ota() {
    return {
      localeError: error$f()
    };
  }
  const error$e = () => {
    const Sizable = {
      string: { unit: "توکي", verb: "ولري" },
      file: { unit: "بایټس", verb: "ولري" },
      array: { unit: "توکي", verb: "ولري" },
      set: { unit: "توکي", verb: "ولري" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "عدد";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "ارې";
          }
          if (data === null) {
            return "null";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    const Nouns = {
      regex: "ورودي",
      email: "بریښنالیک",
      url: "یو آر ال",
      emoji: "ایموجي",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "نیټه او وخت",
      date: "نېټه",
      time: "وخت",
      duration: "موده",
      ipv4: "د IPv4 پته",
      ipv6: "د IPv6 پته",
      cidrv4: "د IPv4 ساحه",
      cidrv6: "د IPv6 ساحه",
      base64: "base64-encoded متن",
      base64url: "base64url-encoded متن",
      json_string: "JSON متن",
      e164: "د E.164 شمېره",
      jwt: "JWT",
      template_literal: "ورودي"
    };
    return (issue2) => {
      var _a3, _b2, _c2, _d2;
      switch (issue2.code) {
        case "invalid_type":
          return `ناسم ورودي: باید ${issue2.expected} وای, مګر ${parsedType2(issue2.input)} ترلاسه شو`;
        case "invalid_value":
          if (issue2.values.length === 1) {
            return `ناسم ورودي: باید ${stringifyPrimitive(issue2.values[0])} وای`;
          }
          return `ناسم انتخاب: باید یو له ${joinValues(issue2.values, "|")} څخه وای`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `ډیر لوی: ${(_a3 = issue2.origin) != null ? _a3 : "ارزښت"} باید ${adj}${issue2.maximum.toString()} ${(_b2 = sizing.unit) != null ? _b2 : "عنصرونه"} ولري`;
          }
          return `ډیر لوی: ${(_c2 = issue2.origin) != null ? _c2 : "ارزښت"} باید ${adj}${issue2.maximum.toString()} وي`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `ډیر کوچنی: ${issue2.origin} باید ${adj}${issue2.minimum.toString()} ${sizing.unit} ولري`;
          }
          return `ډیر کوچنی: ${issue2.origin} باید ${adj}${issue2.minimum.toString()} وي`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with") {
            return `ناسم متن: باید د "${_issue.prefix}" سره پیل شي`;
          }
          if (_issue.format === "ends_with") {
            return `ناسم متن: باید د "${_issue.suffix}" سره پای ته ورسيږي`;
          }
          if (_issue.format === "includes") {
            return `ناسم متن: باید "${_issue.includes}" ولري`;
          }
          if (_issue.format === "regex") {
            return `ناسم متن: باید د ${_issue.pattern} سره مطابقت ولري`;
          }
          return `${(_d2 = Nouns[_issue.format]) != null ? _d2 : issue2.format} ناسم دی`;
        }
        case "not_multiple_of":
          return `ناسم عدد: باید د ${issue2.divisor} مضرب وي`;
        case "unrecognized_keys":
          return `ناسم ${issue2.keys.length > 1 ? "کلیډونه" : "کلیډ"}: ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `ناسم کلیډ په ${issue2.origin} کې`;
        case "invalid_union":
          return `ناسمه ورودي`;
        case "invalid_element":
          return `ناسم عنصر په ${issue2.origin} کې`;
        default:
          return `ناسمه ورودي`;
      }
    };
  };
  function ps() {
    return {
      localeError: error$e()
    };
  }
  const error$d = () => {
    const Sizable = {
      string: { unit: "znaków", verb: "mieć" },
      file: { unit: "bajtów", verb: "mieć" },
      array: { unit: "elementów", verb: "mieć" },
      set: { unit: "elementów", verb: "mieć" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "liczba";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "tablica";
          }
          if (data === null) {
            return "null";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    const Nouns = {
      regex: "wyrażenie",
      email: "adres email",
      url: "URL",
      emoji: "emoji",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "data i godzina w formacie ISO",
      date: "data w formacie ISO",
      time: "godzina w formacie ISO",
      duration: "czas trwania ISO",
      ipv4: "adres IPv4",
      ipv6: "adres IPv6",
      cidrv4: "zakres IPv4",
      cidrv6: "zakres IPv6",
      base64: "ciąg znaków zakodowany w formacie base64",
      base64url: "ciąg znaków zakodowany w formacie base64url",
      json_string: "ciąg znaków w formacie JSON",
      e164: "liczba E.164",
      jwt: "JWT",
      template_literal: "wejście"
    };
    return (issue2) => {
      var _a3, _b2, _c2, _d2, _e, _f, _g;
      switch (issue2.code) {
        case "invalid_type":
          return `Nieprawidłowe dane wejściowe: oczekiwano ${issue2.expected}, otrzymano ${parsedType2(issue2.input)}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `Nieprawidłowe dane wejściowe: oczekiwano ${stringifyPrimitive(issue2.values[0])}`;
          return `Nieprawidłowa opcja: oczekiwano jednej z wartości ${joinValues(issue2.values, "|")}`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `Za duża wartość: oczekiwano, że ${(_a3 = issue2.origin) != null ? _a3 : "wartość"} będzie mieć ${adj}${issue2.maximum.toString()} ${(_b2 = sizing.unit) != null ? _b2 : "elementów"}`;
          }
          return `Zbyt duż(y/a/e): oczekiwano, że ${(_c2 = issue2.origin) != null ? _c2 : "wartość"} będzie wynosić ${adj}${issue2.maximum.toString()}`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `Za mała wartość: oczekiwano, że ${(_d2 = issue2.origin) != null ? _d2 : "wartość"} będzie mieć ${adj}${issue2.minimum.toString()} ${(_e = sizing.unit) != null ? _e : "elementów"}`;
          }
          return `Zbyt mał(y/a/e): oczekiwano, że ${(_f = issue2.origin) != null ? _f : "wartość"} będzie wynosić ${adj}${issue2.minimum.toString()}`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with")
            return `Nieprawidłowy ciąg znaków: musi zaczynać się od "${_issue.prefix}"`;
          if (_issue.format === "ends_with")
            return `Nieprawidłowy ciąg znaków: musi kończyć się na "${_issue.suffix}"`;
          if (_issue.format === "includes")
            return `Nieprawidłowy ciąg znaków: musi zawierać "${_issue.includes}"`;
          if (_issue.format === "regex")
            return `Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${_issue.pattern}`;
          return `Nieprawidłow(y/a/e) ${(_g = Nouns[_issue.format]) != null ? _g : issue2.format}`;
        }
        case "not_multiple_of":
          return `Nieprawidłowa liczba: musi być wielokrotnością ${issue2.divisor}`;
        case "unrecognized_keys":
          return `Nierozpoznane klucze${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `Nieprawidłowy klucz w ${issue2.origin}`;
        case "invalid_union":
          return "Nieprawidłowe dane wejściowe";
        case "invalid_element":
          return `Nieprawidłowa wartość w ${issue2.origin}`;
        default:
          return `Nieprawidłowe dane wejściowe`;
      }
    };
  };
  function pl() {
    return {
      localeError: error$d()
    };
  }
  const error$c = () => {
    const Sizable = {
      string: { unit: "caracteres", verb: "ter" },
      file: { unit: "bytes", verb: "ter" },
      array: { unit: "itens", verb: "ter" },
      set: { unit: "itens", verb: "ter" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "número";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "array";
          }
          if (data === null) {
            return "nulo";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    const Nouns = {
      regex: "padrão",
      email: "endereço de e-mail",
      url: "URL",
      emoji: "emoji",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "data e hora ISO",
      date: "data ISO",
      time: "hora ISO",
      duration: "duração ISO",
      ipv4: "endereço IPv4",
      ipv6: "endereço IPv6",
      cidrv4: "faixa de IPv4",
      cidrv6: "faixa de IPv6",
      base64: "texto codificado em base64",
      base64url: "URL codificada em base64",
      json_string: "texto JSON",
      e164: "número E.164",
      jwt: "JWT",
      template_literal: "entrada"
    };
    return (issue2) => {
      var _a3, _b2, _c2, _d2;
      switch (issue2.code) {
        case "invalid_type":
          return `Tipo inválido: esperado ${issue2.expected}, recebido ${parsedType2(issue2.input)}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `Entrada inválida: esperado ${stringifyPrimitive(issue2.values[0])}`;
          return `Opção inválida: esperada uma das ${joinValues(issue2.values, "|")}`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          if (sizing)
            return `Muito grande: esperado que ${(_a3 = issue2.origin) != null ? _a3 : "valor"} tivesse ${adj}${issue2.maximum.toString()} ${(_b2 = sizing.unit) != null ? _b2 : "elementos"}`;
          return `Muito grande: esperado que ${(_c2 = issue2.origin) != null ? _c2 : "valor"} fosse ${adj}${issue2.maximum.toString()}`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `Muito pequeno: esperado que ${issue2.origin} tivesse ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
          }
          return `Muito pequeno: esperado que ${issue2.origin} fosse ${adj}${issue2.minimum.toString()}`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with")
            return `Texto inválido: deve começar com "${_issue.prefix}"`;
          if (_issue.format === "ends_with")
            return `Texto inválido: deve terminar com "${_issue.suffix}"`;
          if (_issue.format === "includes")
            return `Texto inválido: deve incluir "${_issue.includes}"`;
          if (_issue.format === "regex")
            return `Texto inválido: deve corresponder ao padrão ${_issue.pattern}`;
          return `${(_d2 = Nouns[_issue.format]) != null ? _d2 : issue2.format} inválido`;
        }
        case "not_multiple_of":
          return `Número inválido: deve ser múltiplo de ${issue2.divisor}`;
        case "unrecognized_keys":
          return `Chave${issue2.keys.length > 1 ? "s" : ""} desconhecida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `Chave inválida em ${issue2.origin}`;
        case "invalid_union":
          return "Entrada inválida";
        case "invalid_element":
          return `Valor inválido em ${issue2.origin}`;
        default:
          return `Campo inválido`;
      }
    };
  };
  function pt() {
    return {
      localeError: error$c()
    };
  }
  function getRussianPlural(count, one, few, many) {
    const absCount = Math.abs(count);
    const lastDigit = absCount % 10;
    const lastTwoDigits = absCount % 100;
    if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
      return many;
    }
    if (lastDigit === 1) {
      return one;
    }
    if (lastDigit >= 2 && lastDigit <= 4) {
      return few;
    }
    return many;
  }
  const error$b = () => {
    const Sizable = {
      string: {
        unit: {
          one: "символ",
          few: "символа",
          many: "символов"
        },
        verb: "иметь"
      },
      file: {
        unit: {
          one: "байт",
          few: "байта",
          many: "байт"
        },
        verb: "иметь"
      },
      array: {
        unit: {
          one: "элемент",
          few: "элемента",
          many: "элементов"
        },
        verb: "иметь"
      },
      set: {
        unit: {
          one: "элемент",
          few: "элемента",
          many: "элементов"
        },
        verb: "иметь"
      }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "число";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "массив";
          }
          if (data === null) {
            return "null";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    const Nouns = {
      regex: "ввод",
      email: "email адрес",
      url: "URL",
      emoji: "эмодзи",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "ISO дата и время",
      date: "ISO дата",
      time: "ISO время",
      duration: "ISO длительность",
      ipv4: "IPv4 адрес",
      ipv6: "IPv6 адрес",
      cidrv4: "IPv4 диапазон",
      cidrv6: "IPv6 диапазон",
      base64: "строка в формате base64",
      base64url: "строка в формате base64url",
      json_string: "JSON строка",
      e164: "номер E.164",
      jwt: "JWT",
      template_literal: "ввод"
    };
    return (issue2) => {
      var _a3, _b2, _c2;
      switch (issue2.code) {
        case "invalid_type":
          return `Неверный ввод: ожидалось ${issue2.expected}, получено ${parsedType2(issue2.input)}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `Неверный ввод: ожидалось ${stringifyPrimitive(issue2.values[0])}`;
          return `Неверный вариант: ожидалось одно из ${joinValues(issue2.values, "|")}`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            const maxValue = Number(issue2.maximum);
            const unit = getRussianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
            return `Слишком большое значение: ожидалось, что ${(_a3 = issue2.origin) != null ? _a3 : "значение"} будет иметь ${adj}${issue2.maximum.toString()} ${unit}`;
          }
          return `Слишком большое значение: ожидалось, что ${(_b2 = issue2.origin) != null ? _b2 : "значение"} будет ${adj}${issue2.maximum.toString()}`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            const minValue = Number(issue2.minimum);
            const unit = getRussianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
            return `Слишком маленькое значение: ожидалось, что ${issue2.origin} будет иметь ${adj}${issue2.minimum.toString()} ${unit}`;
          }
          return `Слишком маленькое значение: ожидалось, что ${issue2.origin} будет ${adj}${issue2.minimum.toString()}`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with")
            return `Неверная строка: должна начинаться с "${_issue.prefix}"`;
          if (_issue.format === "ends_with")
            return `Неверная строка: должна заканчиваться на "${_issue.suffix}"`;
          if (_issue.format === "includes")
            return `Неверная строка: должна содержать "${_issue.includes}"`;
          if (_issue.format === "regex")
            return `Неверная строка: должна соответствовать шаблону ${_issue.pattern}`;
          return `Неверный ${(_c2 = Nouns[_issue.format]) != null ? _c2 : issue2.format}`;
        }
        case "not_multiple_of":
          return `Неверное число: должно быть кратным ${issue2.divisor}`;
        case "unrecognized_keys":
          return `Нераспознанн${issue2.keys.length > 1 ? "ые" : "ый"} ключ${issue2.keys.length > 1 ? "и" : ""}: ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `Неверный ключ в ${issue2.origin}`;
        case "invalid_union":
          return "Неверные входные данные";
        case "invalid_element":
          return `Неверное значение в ${issue2.origin}`;
        default:
          return `Неверные входные данные`;
      }
    };
  };
  function ru() {
    return {
      localeError: error$b()
    };
  }
  const error$a = () => {
    const Sizable = {
      string: { unit: "znakov", verb: "imeti" },
      file: { unit: "bajtov", verb: "imeti" },
      array: { unit: "elementov", verb: "imeti" },
      set: { unit: "elementov", verb: "imeti" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "število";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "tabela";
          }
          if (data === null) {
            return "null";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    const Nouns = {
      regex: "vnos",
      email: "e-poštni naslov",
      url: "URL",
      emoji: "emoji",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "ISO datum in čas",
      date: "ISO datum",
      time: "ISO čas",
      duration: "ISO trajanje",
      ipv4: "IPv4 naslov",
      ipv6: "IPv6 naslov",
      cidrv4: "obseg IPv4",
      cidrv6: "obseg IPv6",
      base64: "base64 kodiran niz",
      base64url: "base64url kodiran niz",
      json_string: "JSON niz",
      e164: "E.164 številka",
      jwt: "JWT",
      template_literal: "vnos"
    };
    return (issue2) => {
      var _a3, _b2, _c2, _d2;
      switch (issue2.code) {
        case "invalid_type":
          return `Neveljaven vnos: pričakovano ${issue2.expected}, prejeto ${parsedType2(issue2.input)}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `Neveljaven vnos: pričakovano ${stringifyPrimitive(issue2.values[0])}`;
          return `Neveljavna možnost: pričakovano eno izmed ${joinValues(issue2.values, "|")}`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          if (sizing)
            return `Preveliko: pričakovano, da bo ${(_a3 = issue2.origin) != null ? _a3 : "vrednost"} imelo ${adj}${issue2.maximum.toString()} ${(_b2 = sizing.unit) != null ? _b2 : "elementov"}`;
          return `Preveliko: pričakovano, da bo ${(_c2 = issue2.origin) != null ? _c2 : "vrednost"} ${adj}${issue2.maximum.toString()}`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `Premajhno: pričakovano, da bo ${issue2.origin} imelo ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
          }
          return `Premajhno: pričakovano, da bo ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with") {
            return `Neveljaven niz: mora se začeti z "${_issue.prefix}"`;
          }
          if (_issue.format === "ends_with")
            return `Neveljaven niz: mora se končati z "${_issue.suffix}"`;
          if (_issue.format === "includes")
            return `Neveljaven niz: mora vsebovati "${_issue.includes}"`;
          if (_issue.format === "regex")
            return `Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`;
          return `Neveljaven ${(_d2 = Nouns[_issue.format]) != null ? _d2 : issue2.format}`;
        }
        case "not_multiple_of":
          return `Neveljavno število: mora biti večkratnik ${issue2.divisor}`;
        case "unrecognized_keys":
          return `Neprepoznan${issue2.keys.length > 1 ? "i ključi" : " ključ"}: ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `Neveljaven ključ v ${issue2.origin}`;
        case "invalid_union":
          return "Neveljaven vnos";
        case "invalid_element":
          return `Neveljavna vrednost v ${issue2.origin}`;
        default:
          return "Neveljaven vnos";
      }
    };
  };
  function sl() {
    return {
      localeError: error$a()
    };
  }
  const error$9 = () => {
    const Sizable = {
      string: { unit: "tecken", verb: "att ha" },
      file: { unit: "bytes", verb: "att ha" },
      array: { unit: "objekt", verb: "att innehålla" },
      set: { unit: "objekt", verb: "att innehålla" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "antal";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "lista";
          }
          if (data === null) {
            return "null";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    const Nouns = {
      regex: "reguljärt uttryck",
      email: "e-postadress",
      url: "URL",
      emoji: "emoji",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "ISO-datum och tid",
      date: "ISO-datum",
      time: "ISO-tid",
      duration: "ISO-varaktighet",
      ipv4: "IPv4-intervall",
      ipv6: "IPv6-intervall",
      cidrv4: "IPv4-spektrum",
      cidrv6: "IPv6-spektrum",
      base64: "base64-kodad sträng",
      base64url: "base64url-kodad sträng",
      json_string: "JSON-sträng",
      e164: "E.164-nummer",
      jwt: "JWT",
      template_literal: "mall-literal"
    };
    return (issue2) => {
      var _a3, _b2, _c2, _d2, _e, _f, _g, _h;
      switch (issue2.code) {
        case "invalid_type":
          return `Ogiltig inmatning: förväntat ${issue2.expected}, fick ${parsedType2(issue2.input)}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `Ogiltig inmatning: förväntat ${stringifyPrimitive(issue2.values[0])}`;
          return `Ogiltigt val: förväntade en av ${joinValues(issue2.values, "|")}`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `För stor(t): förväntade ${(_a3 = issue2.origin) != null ? _a3 : "värdet"} att ha ${adj}${issue2.maximum.toString()} ${(_b2 = sizing.unit) != null ? _b2 : "element"}`;
          }
          return `För stor(t): förväntat ${(_c2 = issue2.origin) != null ? _c2 : "värdet"} att ha ${adj}${issue2.maximum.toString()}`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `För lite(t): förväntade ${(_d2 = issue2.origin) != null ? _d2 : "värdet"} att ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
          }
          return `För lite(t): förväntade ${(_e = issue2.origin) != null ? _e : "värdet"} att ha ${adj}${issue2.minimum.toString()}`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with") {
            return `Ogiltig sträng: måste börja med "${_issue.prefix}"`;
          }
          if (_issue.format === "ends_with")
            return `Ogiltig sträng: måste sluta med "${_issue.suffix}"`;
          if (_issue.format === "includes")
            return `Ogiltig sträng: måste innehålla "${_issue.includes}"`;
          if (_issue.format === "regex")
            return `Ogiltig sträng: måste matcha mönstret "${_issue.pattern}"`;
          return `Ogiltig(t) ${(_f = Nouns[_issue.format]) != null ? _f : issue2.format}`;
        }
        case "not_multiple_of":
          return `Ogiltigt tal: måste vara en multipel av ${issue2.divisor}`;
        case "unrecognized_keys":
          return `${issue2.keys.length > 1 ? "Okända nycklar" : "Okänd nyckel"}: ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `Ogiltig nyckel i ${(_g = issue2.origin) != null ? _g : "värdet"}`;
        case "invalid_union":
          return "Ogiltig input";
        case "invalid_element":
          return `Ogiltigt värde i ${(_h = issue2.origin) != null ? _h : "värdet"}`;
        default:
          return `Ogiltig input`;
      }
    };
  };
  function sv() {
    return {
      localeError: error$9()
    };
  }
  const error$8 = () => {
    const Sizable = {
      string: { unit: "எழுத்துக்கள்", verb: "கொண்டிருக்க வேண்டும்" },
      file: { unit: "பைட்டுகள்", verb: "கொண்டிருக்க வேண்டும்" },
      array: { unit: "உறுப்புகள்", verb: "கொண்டிருக்க வேண்டும்" },
      set: { unit: "உறுப்புகள்", verb: "கொண்டிருக்க வேண்டும்" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "எண் அல்லாதது" : "எண்";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "அணி";
          }
          if (data === null) {
            return "வெறுமை";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    const Nouns = {
      regex: "உள்ளீடு",
      email: "மின்னஞ்சல் முகவரி",
      url: "URL",
      emoji: "emoji",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "ISO தேதி நேரம்",
      date: "ISO தேதி",
      time: "ISO நேரம்",
      duration: "ISO கால அளவு",
      ipv4: "IPv4 முகவரி",
      ipv6: "IPv6 முகவரி",
      cidrv4: "IPv4 வரம்பு",
      cidrv6: "IPv6 வரம்பு",
      base64: "base64-encoded சரம்",
      base64url: "base64url-encoded சரம்",
      json_string: "JSON சரம்",
      e164: "E.164 எண்",
      jwt: "JWT",
      template_literal: "input"
    };
    return (issue2) => {
      var _a3, _b2, _c2, _d2;
      switch (issue2.code) {
        case "invalid_type":
          return `தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${issue2.expected}, பெறப்பட்டது ${parsedType2(issue2.input)}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${stringifyPrimitive(issue2.values[0])}`;
          return `தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${joinValues(issue2.values, "|")} இல் ஒன்று`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `மிக பெரியது: எதிர்பார்க்கப்பட்டது ${(_a3 = issue2.origin) != null ? _a3 : "மதிப்பு"} ${adj}${issue2.maximum.toString()} ${(_b2 = sizing.unit) != null ? _b2 : "உறுப்புகள்"} ஆக இருக்க வேண்டும்`;
          }
          return `மிக பெரியது: எதிர்பார்க்கப்பட்டது ${(_c2 = issue2.origin) != null ? _c2 : "மதிப்பு"} ${adj}${issue2.maximum.toString()} ஆக இருக்க வேண்டும்`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ஆக இருக்க வேண்டும்`;
          }
          return `மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${issue2.origin} ${adj}${issue2.minimum.toString()} ஆக இருக்க வேண்டும்`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with")
            return `தவறான சரம்: "${_issue.prefix}" இல் தொடங்க வேண்டும்`;
          if (_issue.format === "ends_with")
            return `தவறான சரம்: "${_issue.suffix}" இல் முடிவடைய வேண்டும்`;
          if (_issue.format === "includes")
            return `தவறான சரம்: "${_issue.includes}" ஐ உள்ளடக்க வேண்டும்`;
          if (_issue.format === "regex")
            return `தவறான சரம்: ${_issue.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`;
          return `தவறான ${(_d2 = Nouns[_issue.format]) != null ? _d2 : issue2.format}`;
        }
        case "not_multiple_of":
          return `தவறான எண்: ${issue2.divisor} இன் பலமாக இருக்க வேண்டும்`;
        case "unrecognized_keys":
          return `அடையாளம் தெரியாத விசை${issue2.keys.length > 1 ? "கள்" : ""}: ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `${issue2.origin} இல் தவறான விசை`;
        case "invalid_union":
          return "தவறான உள்ளீடு";
        case "invalid_element":
          return `${issue2.origin} இல் தவறான மதிப்பு`;
        default:
          return `தவறான உள்ளீடு`;
      }
    };
  };
  function ta() {
    return {
      localeError: error$8()
    };
  }
  const error$7 = () => {
    const Sizable = {
      string: { unit: "ตัวอักษร", verb: "ควรมี" },
      file: { unit: "ไบต์", verb: "ควรมี" },
      array: { unit: "รายการ", verb: "ควรมี" },
      set: { unit: "รายการ", verb: "ควรมี" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "ไม่ใช่ตัวเลข (NaN)" : "ตัวเลข";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "อาร์เรย์ (Array)";
          }
          if (data === null) {
            return "ไม่มีค่า (null)";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    const Nouns = {
      regex: "ข้อมูลที่ป้อน",
      email: "ที่อยู่อีเมล",
      url: "URL",
      emoji: "อิโมจิ",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "วันที่เวลาแบบ ISO",
      date: "วันที่แบบ ISO",
      time: "เวลาแบบ ISO",
      duration: "ช่วงเวลาแบบ ISO",
      ipv4: "ที่อยู่ IPv4",
      ipv6: "ที่อยู่ IPv6",
      cidrv4: "ช่วง IP แบบ IPv4",
      cidrv6: "ช่วง IP แบบ IPv6",
      base64: "ข้อความแบบ Base64",
      base64url: "ข้อความแบบ Base64 สำหรับ URL",
      json_string: "ข้อความแบบ JSON",
      e164: "เบอร์โทรศัพท์ระหว่างประเทศ (E.164)",
      jwt: "โทเคน JWT",
      template_literal: "ข้อมูลที่ป้อน"
    };
    return (issue2) => {
      var _a3, _b2, _c2, _d2;
      switch (issue2.code) {
        case "invalid_type":
          return `ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${issue2.expected} แต่ได้รับ ${parsedType2(issue2.input)}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `ค่าไม่ถูกต้อง: ควรเป็น ${stringifyPrimitive(issue2.values[0])}`;
          return `ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${joinValues(issue2.values, "|")}`;
        case "too_big": {
          const adj = issue2.inclusive ? "ไม่เกิน" : "น้อยกว่า";
          const sizing = getSizing(issue2.origin);
          if (sizing)
            return `เกินกำหนด: ${(_a3 = issue2.origin) != null ? _a3 : "ค่า"} ควรมี${adj} ${issue2.maximum.toString()} ${(_b2 = sizing.unit) != null ? _b2 : "รายการ"}`;
          return `เกินกำหนด: ${(_c2 = issue2.origin) != null ? _c2 : "ค่า"} ควรมี${adj} ${issue2.maximum.toString()}`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? "อย่างน้อย" : "มากกว่า";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `น้อยกว่ากำหนด: ${issue2.origin} ควรมี${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
          }
          return `น้อยกว่ากำหนด: ${issue2.origin} ควรมี${adj} ${issue2.minimum.toString()}`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with") {
            return `รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${_issue.prefix}"`;
          }
          if (_issue.format === "ends_with")
            return `รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${_issue.suffix}"`;
          if (_issue.format === "includes")
            return `รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${_issue.includes}" อยู่ในข้อความ`;
          if (_issue.format === "regex")
            return `รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${_issue.pattern}`;
          return `รูปแบบไม่ถูกต้อง: ${(_d2 = Nouns[_issue.format]) != null ? _d2 : issue2.format}`;
        }
        case "not_multiple_of":
          return `ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${issue2.divisor} ได้ลงตัว`;
        case "unrecognized_keys":
          return `พบคีย์ที่ไม่รู้จัก: ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `คีย์ไม่ถูกต้องใน ${issue2.origin}`;
        case "invalid_union":
          return "ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้";
        case "invalid_element":
          return `ข้อมูลไม่ถูกต้องใน ${issue2.origin}`;
        default:
          return `ข้อมูลไม่ถูกต้อง`;
      }
    };
  };
  function th() {
    return {
      localeError: error$7()
    };
  }
  const parsedType = (data) => {
    const t = typeof data;
    switch (t) {
      case "number": {
        return Number.isNaN(data) ? "NaN" : "number";
      }
      case "object": {
        if (Array.isArray(data)) {
          return "array";
        }
        if (data === null) {
          return "null";
        }
        if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
          return data.constructor.name;
        }
      }
    }
    return t;
  };
  const error$6 = () => {
    const Sizable = {
      string: { unit: "karakter", verb: "olmalı" },
      file: { unit: "bayt", verb: "olmalı" },
      array: { unit: "öğe", verb: "olmalı" },
      set: { unit: "öğe", verb: "olmalı" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const Nouns = {
      regex: "girdi",
      email: "e-posta adresi",
      url: "URL",
      emoji: "emoji",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "ISO tarih ve saat",
      date: "ISO tarih",
      time: "ISO saat",
      duration: "ISO süre",
      ipv4: "IPv4 adresi",
      ipv6: "IPv6 adresi",
      cidrv4: "IPv4 aralığı",
      cidrv6: "IPv6 aralığı",
      base64: "base64 ile şifrelenmiş metin",
      base64url: "base64url ile şifrelenmiş metin",
      json_string: "JSON dizesi",
      e164: "E.164 sayısı",
      jwt: "JWT",
      template_literal: "Şablon dizesi"
    };
    return (issue2) => {
      var _a3, _b2, _c2, _d2;
      switch (issue2.code) {
        case "invalid_type":
          return `Geçersiz değer: beklenen ${issue2.expected}, alınan ${parsedType(issue2.input)}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `Geçersiz değer: beklenen ${stringifyPrimitive(issue2.values[0])}`;
          return `Geçersiz seçenek: aşağıdakilerden biri olmalı: ${joinValues(issue2.values, "|")}`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          if (sizing)
            return `Çok büyük: beklenen ${(_a3 = issue2.origin) != null ? _a3 : "değer"} ${adj}${issue2.maximum.toString()} ${(_b2 = sizing.unit) != null ? _b2 : "öğe"}`;
          return `Çok büyük: beklenen ${(_c2 = issue2.origin) != null ? _c2 : "değer"} ${adj}${issue2.maximum.toString()}`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          if (sizing)
            return `Çok küçük: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
          return `Çok küçük: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with")
            return `Geçersiz metin: "${_issue.prefix}" ile başlamalı`;
          if (_issue.format === "ends_with")
            return `Geçersiz metin: "${_issue.suffix}" ile bitmeli`;
          if (_issue.format === "includes")
            return `Geçersiz metin: "${_issue.includes}" içermeli`;
          if (_issue.format === "regex")
            return `Geçersiz metin: ${_issue.pattern} desenine uymalı`;
          return `Geçersiz ${(_d2 = Nouns[_issue.format]) != null ? _d2 : issue2.format}`;
        }
        case "not_multiple_of":
          return `Geçersiz sayı: ${issue2.divisor} ile tam bölünebilmeli`;
        case "unrecognized_keys":
          return `Tanınmayan anahtar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `${issue2.origin} içinde geçersiz anahtar`;
        case "invalid_union":
          return "Geçersiz değer";
        case "invalid_element":
          return `${issue2.origin} içinde geçersiz değer`;
        default:
          return `Geçersiz değer`;
      }
    };
  };
  function tr() {
    return {
      localeError: error$6()
    };
  }
  const error$5 = () => {
    const Sizable = {
      string: { unit: "символів", verb: "матиме" },
      file: { unit: "байтів", verb: "матиме" },
      array: { unit: "елементів", verb: "матиме" },
      set: { unit: "елементів", verb: "матиме" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "число";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "масив";
          }
          if (data === null) {
            return "null";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    const Nouns = {
      regex: "вхідні дані",
      email: "адреса електронної пошти",
      url: "URL",
      emoji: "емодзі",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "дата та час ISO",
      date: "дата ISO",
      time: "час ISO",
      duration: "тривалість ISO",
      ipv4: "адреса IPv4",
      ipv6: "адреса IPv6",
      cidrv4: "діапазон IPv4",
      cidrv6: "діапазон IPv6",
      base64: "рядок у кодуванні base64",
      base64url: "рядок у кодуванні base64url",
      json_string: "рядок JSON",
      e164: "номер E.164",
      jwt: "JWT",
      template_literal: "вхідні дані"
    };
    return (issue2) => {
      var _a3, _b2, _c2, _d2;
      switch (issue2.code) {
        case "invalid_type":
          return `Неправильні вхідні дані: очікується ${issue2.expected}, отримано ${parsedType2(issue2.input)}`;
        // return `Неправильні вхідні дані: очікується ${issue.expected}, отримано ${util.getParsedType(issue.input)}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `Неправильні вхідні дані: очікується ${stringifyPrimitive(issue2.values[0])}`;
          return `Неправильна опція: очікується одне з ${joinValues(issue2.values, "|")}`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          if (sizing)
            return `Занадто велике: очікується, що ${(_a3 = issue2.origin) != null ? _a3 : "значення"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${(_b2 = sizing.unit) != null ? _b2 : "елементів"}`;
          return `Занадто велике: очікується, що ${(_c2 = issue2.origin) != null ? _c2 : "значення"} буде ${adj}${issue2.maximum.toString()}`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `Занадто мале: очікується, що ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
          }
          return `Занадто мале: очікується, що ${issue2.origin} буде ${adj}${issue2.minimum.toString()}`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with")
            return `Неправильний рядок: повинен починатися з "${_issue.prefix}"`;
          if (_issue.format === "ends_with")
            return `Неправильний рядок: повинен закінчуватися на "${_issue.suffix}"`;
          if (_issue.format === "includes")
            return `Неправильний рядок: повинен містити "${_issue.includes}"`;
          if (_issue.format === "regex")
            return `Неправильний рядок: повинен відповідати шаблону ${_issue.pattern}`;
          return `Неправильний ${(_d2 = Nouns[_issue.format]) != null ? _d2 : issue2.format}`;
        }
        case "not_multiple_of":
          return `Неправильне число: повинно бути кратним ${issue2.divisor}`;
        case "unrecognized_keys":
          return `Нерозпізнаний ключ${issue2.keys.length > 1 ? "і" : ""}: ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `Неправильний ключ у ${issue2.origin}`;
        case "invalid_union":
          return "Неправильні вхідні дані";
        case "invalid_element":
          return `Неправильне значення у ${issue2.origin}`;
        default:
          return `Неправильні вхідні дані`;
      }
    };
  };
  function uk() {
    return {
      localeError: error$5()
    };
  }
  function ua() {
    return uk();
  }
  const error$4 = () => {
    const Sizable = {
      string: { unit: "حروف", verb: "ہونا" },
      file: { unit: "بائٹس", verb: "ہونا" },
      array: { unit: "آئٹمز", verb: "ہونا" },
      set: { unit: "آئٹمز", verb: "ہونا" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "نمبر";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "آرے";
          }
          if (data === null) {
            return "نل";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    const Nouns = {
      regex: "ان پٹ",
      email: "ای میل ایڈریس",
      url: "یو آر ایل",
      emoji: "ایموجی",
      uuid: "یو یو آئی ڈی",
      uuidv4: "یو یو آئی ڈی وی 4",
      uuidv6: "یو یو آئی ڈی وی 6",
      nanoid: "نینو آئی ڈی",
      guid: "جی یو آئی ڈی",
      cuid: "سی یو آئی ڈی",
      cuid2: "سی یو آئی ڈی 2",
      ulid: "یو ایل آئی ڈی",
      xid: "ایکس آئی ڈی",
      ksuid: "کے ایس یو آئی ڈی",
      datetime: "آئی ایس او ڈیٹ ٹائم",
      date: "آئی ایس او تاریخ",
      time: "آئی ایس او وقت",
      duration: "آئی ایس او مدت",
      ipv4: "آئی پی وی 4 ایڈریس",
      ipv6: "آئی پی وی 6 ایڈریس",
      cidrv4: "آئی پی وی 4 رینج",
      cidrv6: "آئی پی وی 6 رینج",
      base64: "بیس 64 ان کوڈڈ سٹرنگ",
      base64url: "بیس 64 یو آر ایل ان کوڈڈ سٹرنگ",
      json_string: "جے ایس او این سٹرنگ",
      e164: "ای 164 نمبر",
      jwt: "جے ڈبلیو ٹی",
      template_literal: "ان پٹ"
    };
    return (issue2) => {
      var _a3, _b2, _c2, _d2;
      switch (issue2.code) {
        case "invalid_type":
          return `غلط ان پٹ: ${issue2.expected} متوقع تھا، ${parsedType2(issue2.input)} موصول ہوا`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `غلط ان پٹ: ${stringifyPrimitive(issue2.values[0])} متوقع تھا`;
          return `غلط آپشن: ${joinValues(issue2.values, "|")} میں سے ایک متوقع تھا`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          if (sizing)
            return `بہت بڑا: ${(_a3 = issue2.origin) != null ? _a3 : "ویلیو"} کے ${adj}${issue2.maximum.toString()} ${(_b2 = sizing.unit) != null ? _b2 : "عناصر"} ہونے متوقع تھے`;
          return `بہت بڑا: ${(_c2 = issue2.origin) != null ? _c2 : "ویلیو"} کا ${adj}${issue2.maximum.toString()} ہونا متوقع تھا`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `بہت چھوٹا: ${issue2.origin} کے ${adj}${issue2.minimum.toString()} ${sizing.unit} ہونے متوقع تھے`;
          }
          return `بہت چھوٹا: ${issue2.origin} کا ${adj}${issue2.minimum.toString()} ہونا متوقع تھا`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with") {
            return `غلط سٹرنگ: "${_issue.prefix}" سے شروع ہونا چاہیے`;
          }
          if (_issue.format === "ends_with")
            return `غلط سٹرنگ: "${_issue.suffix}" پر ختم ہونا چاہیے`;
          if (_issue.format === "includes")
            return `غلط سٹرنگ: "${_issue.includes}" شامل ہونا چاہیے`;
          if (_issue.format === "regex")
            return `غلط سٹرنگ: پیٹرن ${_issue.pattern} سے میچ ہونا چاہیے`;
          return `غلط ${(_d2 = Nouns[_issue.format]) != null ? _d2 : issue2.format}`;
        }
        case "not_multiple_of":
          return `غلط نمبر: ${issue2.divisor} کا مضاعف ہونا چاہیے`;
        case "unrecognized_keys":
          return `غیر تسلیم شدہ کی${issue2.keys.length > 1 ? "ز" : ""}: ${joinValues(issue2.keys, "، ")}`;
        case "invalid_key":
          return `${issue2.origin} میں غلط کی`;
        case "invalid_union":
          return "غلط ان پٹ";
        case "invalid_element":
          return `${issue2.origin} میں غلط ویلیو`;
        default:
          return `غلط ان پٹ`;
      }
    };
  };
  function ur() {
    return {
      localeError: error$4()
    };
  }
  const error$3 = () => {
    const Sizable = {
      string: { unit: "ký tự", verb: "có" },
      file: { unit: "byte", verb: "có" },
      array: { unit: "phần tử", verb: "có" },
      set: { unit: "phần tử", verb: "có" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "số";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "mảng";
          }
          if (data === null) {
            return "null";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    const Nouns = {
      regex: "đầu vào",
      email: "địa chỉ email",
      url: "URL",
      emoji: "emoji",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "ngày giờ ISO",
      date: "ngày ISO",
      time: "giờ ISO",
      duration: "khoảng thời gian ISO",
      ipv4: "địa chỉ IPv4",
      ipv6: "địa chỉ IPv6",
      cidrv4: "dải IPv4",
      cidrv6: "dải IPv6",
      base64: "chuỗi mã hóa base64",
      base64url: "chuỗi mã hóa base64url",
      json_string: "chuỗi JSON",
      e164: "số E.164",
      jwt: "JWT",
      template_literal: "đầu vào"
    };
    return (issue2) => {
      var _a3, _b2, _c2, _d2;
      switch (issue2.code) {
        case "invalid_type":
          return `Đầu vào không hợp lệ: mong đợi ${issue2.expected}, nhận được ${parsedType2(issue2.input)}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `Đầu vào không hợp lệ: mong đợi ${stringifyPrimitive(issue2.values[0])}`;
          return `Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${joinValues(issue2.values, "|")}`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          if (sizing)
            return `Quá lớn: mong đợi ${(_a3 = issue2.origin) != null ? _a3 : "giá trị"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${(_b2 = sizing.unit) != null ? _b2 : "phần tử"}`;
          return `Quá lớn: mong đợi ${(_c2 = issue2.origin) != null ? _c2 : "giá trị"} ${adj}${issue2.maximum.toString()}`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `Quá nhỏ: mong đợi ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
          }
          return `Quá nhỏ: mong đợi ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with")
            return `Chuỗi không hợp lệ: phải bắt đầu bằng "${_issue.prefix}"`;
          if (_issue.format === "ends_with")
            return `Chuỗi không hợp lệ: phải kết thúc bằng "${_issue.suffix}"`;
          if (_issue.format === "includes")
            return `Chuỗi không hợp lệ: phải bao gồm "${_issue.includes}"`;
          if (_issue.format === "regex")
            return `Chuỗi không hợp lệ: phải khớp với mẫu ${_issue.pattern}`;
          return `${(_d2 = Nouns[_issue.format]) != null ? _d2 : issue2.format} không hợp lệ`;
        }
        case "not_multiple_of":
          return `Số không hợp lệ: phải là bội số của ${issue2.divisor}`;
        case "unrecognized_keys":
          return `Khóa không được nhận dạng: ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `Khóa không hợp lệ trong ${issue2.origin}`;
        case "invalid_union":
          return "Đầu vào không hợp lệ";
        case "invalid_element":
          return `Giá trị không hợp lệ trong ${issue2.origin}`;
        default:
          return `Đầu vào không hợp lệ`;
      }
    };
  };
  function vi() {
    return {
      localeError: error$3()
    };
  }
  const error$2 = () => {
    const Sizable = {
      string: { unit: "字符", verb: "包含" },
      file: { unit: "字节", verb: "包含" },
      array: { unit: "项", verb: "包含" },
      set: { unit: "项", verb: "包含" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "非数字(NaN)" : "数字";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "数组";
          }
          if (data === null) {
            return "空值(null)";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    const Nouns = {
      regex: "输入",
      email: "电子邮件",
      url: "URL",
      emoji: "表情符号",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "ISO日期时间",
      date: "ISO日期",
      time: "ISO时间",
      duration: "ISO时长",
      ipv4: "IPv4地址",
      ipv6: "IPv6地址",
      cidrv4: "IPv4网段",
      cidrv6: "IPv6网段",
      base64: "base64编码字符串",
      base64url: "base64url编码字符串",
      json_string: "JSON字符串",
      e164: "E.164号码",
      jwt: "JWT",
      template_literal: "输入"
    };
    return (issue2) => {
      var _a3, _b2, _c2, _d2;
      switch (issue2.code) {
        case "invalid_type":
          return `无效输入：期望 ${issue2.expected}，实际接收 ${parsedType2(issue2.input)}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `无效输入：期望 ${stringifyPrimitive(issue2.values[0])}`;
          return `无效选项：期望以下之一 ${joinValues(issue2.values, "|")}`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          if (sizing)
            return `数值过大：期望 ${(_a3 = issue2.origin) != null ? _a3 : "值"} ${adj}${issue2.maximum.toString()} ${(_b2 = sizing.unit) != null ? _b2 : "个元素"}`;
          return `数值过大：期望 ${(_c2 = issue2.origin) != null ? _c2 : "值"} ${adj}${issue2.maximum.toString()}`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `数值过小：期望 ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
          }
          return `数值过小：期望 ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with")
            return `无效字符串：必须以 "${_issue.prefix}" 开头`;
          if (_issue.format === "ends_with")
            return `无效字符串：必须以 "${_issue.suffix}" 结尾`;
          if (_issue.format === "includes")
            return `无效字符串：必须包含 "${_issue.includes}"`;
          if (_issue.format === "regex")
            return `无效字符串：必须满足正则表达式 ${_issue.pattern}`;
          return `无效${(_d2 = Nouns[_issue.format]) != null ? _d2 : issue2.format}`;
        }
        case "not_multiple_of":
          return `无效数字：必须是 ${issue2.divisor} 的倍数`;
        case "unrecognized_keys":
          return `出现未知的键(key): ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `${issue2.origin} 中的键(key)无效`;
        case "invalid_union":
          return "无效输入";
        case "invalid_element":
          return `${issue2.origin} 中包含无效值(value)`;
        default:
          return `无效输入`;
      }
    };
  };
  function zhCN() {
    return {
      localeError: error$2()
    };
  }
  const error$1 = () => {
    const Sizable = {
      string: { unit: "字元", verb: "擁有" },
      file: { unit: "位元組", verb: "擁有" },
      array: { unit: "項目", verb: "擁有" },
      set: { unit: "項目", verb: "擁有" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "number";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "array";
          }
          if (data === null) {
            return "null";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    const Nouns = {
      regex: "輸入",
      email: "郵件地址",
      url: "URL",
      emoji: "emoji",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "ISO 日期時間",
      date: "ISO 日期",
      time: "ISO 時間",
      duration: "ISO 期間",
      ipv4: "IPv4 位址",
      ipv6: "IPv6 位址",
      cidrv4: "IPv4 範圍",
      cidrv6: "IPv6 範圍",
      base64: "base64 編碼字串",
      base64url: "base64url 編碼字串",
      json_string: "JSON 字串",
      e164: "E.164 數值",
      jwt: "JWT",
      template_literal: "輸入"
    };
    return (issue2) => {
      var _a3, _b2, _c2, _d2;
      switch (issue2.code) {
        case "invalid_type":
          return `無效的輸入值：預期為 ${issue2.expected}，但收到 ${parsedType2(issue2.input)}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `無效的輸入值：預期為 ${stringifyPrimitive(issue2.values[0])}`;
          return `無效的選項：預期為以下其中之一 ${joinValues(issue2.values, "|")}`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          if (sizing)
            return `數值過大：預期 ${(_a3 = issue2.origin) != null ? _a3 : "值"} 應為 ${adj}${issue2.maximum.toString()} ${(_b2 = sizing.unit) != null ? _b2 : "個元素"}`;
          return `數值過大：預期 ${(_c2 = issue2.origin) != null ? _c2 : "值"} 應為 ${adj}${issue2.maximum.toString()}`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          if (sizing) {
            return `數值過小：預期 ${issue2.origin} 應為 ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
          }
          return `數值過小：預期 ${issue2.origin} 應為 ${adj}${issue2.minimum.toString()}`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with") {
            return `無效的字串：必須以 "${_issue.prefix}" 開頭`;
          }
          if (_issue.format === "ends_with")
            return `無效的字串：必須以 "${_issue.suffix}" 結尾`;
          if (_issue.format === "includes")
            return `無效的字串：必須包含 "${_issue.includes}"`;
          if (_issue.format === "regex")
            return `無效的字串：必須符合格式 ${_issue.pattern}`;
          return `無效的 ${(_d2 = Nouns[_issue.format]) != null ? _d2 : issue2.format}`;
        }
        case "not_multiple_of":
          return `無效的數字：必須為 ${issue2.divisor} 的倍數`;
        case "unrecognized_keys":
          return `無法識別的鍵值${issue2.keys.length > 1 ? "們" : ""}：${joinValues(issue2.keys, "、")}`;
        case "invalid_key":
          return `${issue2.origin} 中有無效的鍵值`;
        case "invalid_union":
          return "無效的輸入值";
        case "invalid_element":
          return `${issue2.origin} 中有無效的值`;
        default:
          return `無效的輸入值`;
      }
    };
  };
  function zhTW() {
    return {
      localeError: error$1()
    };
  }
  const error = () => {
    const Sizable = {
      string: { unit: "àmi", verb: "ní" },
      file: { unit: "bytes", verb: "ní" },
      array: { unit: "nkan", verb: "ní" },
      set: { unit: "nkan", verb: "ní" }
    };
    function getSizing(origin) {
      var _a3;
      return (_a3 = Sizable[origin]) != null ? _a3 : null;
    }
    const parsedType2 = (data) => {
      const t = typeof data;
      switch (t) {
        case "number": {
          return Number.isNaN(data) ? "NaN" : "nọ́mbà";
        }
        case "object": {
          if (Array.isArray(data)) {
            return "akopọ";
          }
          if (data === null) {
            return "null";
          }
          if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
            return data.constructor.name;
          }
        }
      }
      return t;
    };
    const Nouns = {
      regex: "ẹ̀rọ ìbáwọlé",
      email: "àdírẹ́sì ìmẹ́lì",
      url: "URL",
      emoji: "emoji",
      uuid: "UUID",
      uuidv4: "UUIDv4",
      uuidv6: "UUIDv6",
      nanoid: "nanoid",
      guid: "GUID",
      cuid: "cuid",
      cuid2: "cuid2",
      ulid: "ULID",
      xid: "XID",
      ksuid: "KSUID",
      datetime: "àkókò ISO",
      date: "ọjọ́ ISO",
      time: "àkókò ISO",
      duration: "àkókò tó pé ISO",
      ipv4: "àdírẹ́sì IPv4",
      ipv6: "àdírẹ́sì IPv6",
      cidrv4: "àgbègbè IPv4",
      cidrv6: "àgbègbè IPv6",
      base64: "ọ̀rọ̀ tí a kọ́ ní base64",
      base64url: "ọ̀rọ̀ base64url",
      json_string: "ọ̀rọ̀ JSON",
      e164: "nọ́mbà E.164",
      jwt: "JWT",
      template_literal: "ẹ̀rọ ìbáwọlé"
    };
    return (issue2) => {
      var _a3, _b2;
      switch (issue2.code) {
        case "invalid_type":
          return `Ìbáwọlé aṣìṣe: a ní láti fi ${issue2.expected}, àmọ̀ a rí ${parsedType2(issue2.input)}`;
        case "invalid_value":
          if (issue2.values.length === 1)
            return `Ìbáwọlé aṣìṣe: a ní láti fi ${stringifyPrimitive(issue2.values[0])}`;
          return `Àṣàyàn aṣìṣe: yan ọ̀kan lára ${joinValues(issue2.values, "|")}`;
        case "too_big": {
          const adj = issue2.inclusive ? "<=" : "<";
          const sizing = getSizing(issue2.origin);
          if (sizing)
            return `Tó pọ̀ jù: a ní láti jẹ́ pé ${(_a3 = issue2.origin) != null ? _a3 : "iye"} ${sizing.verb} ${adj}${issue2.maximum} ${sizing.unit}`;
          return `Tó pọ̀ jù: a ní láti jẹ́ ${adj}${issue2.maximum}`;
        }
        case "too_small": {
          const adj = issue2.inclusive ? ">=" : ">";
          const sizing = getSizing(issue2.origin);
          if (sizing)
            return `Kéré ju: a ní láti jẹ́ pé ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum} ${sizing.unit}`;
          return `Kéré ju: a ní láti jẹ́ ${adj}${issue2.minimum}`;
        }
        case "invalid_format": {
          const _issue = issue2;
          if (_issue.format === "starts_with")
            return `Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bẹ̀rẹ̀ pẹ̀lú "${_issue.prefix}"`;
          if (_issue.format === "ends_with")
            return `Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ parí pẹ̀lú "${_issue.suffix}"`;
          if (_issue.format === "includes")
            return `Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ ní "${_issue.includes}"`;
          if (_issue.format === "regex")
            return `Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bá àpẹẹrẹ mu ${_issue.pattern}`;
          return `Aṣìṣe: ${(_b2 = Nouns[_issue.format]) != null ? _b2 : issue2.format}`;
        }
        case "not_multiple_of":
          return `Nọ́mbà aṣìṣe: gbọ́dọ̀ jẹ́ èyà pípín ti ${issue2.divisor}`;
        case "unrecognized_keys":
          return `Bọtìnì àìmọ̀: ${joinValues(issue2.keys, ", ")}`;
        case "invalid_key":
          return `Bọtìnì aṣìṣe nínú ${issue2.origin}`;
        case "invalid_union":
          return "Ìbáwọlé aṣìṣe";
        case "invalid_element":
          return `Iye aṣìṣe nínú ${issue2.origin}`;
        default:
          return "Ìbáwọlé aṣìṣe";
      }
    };
  };
  function yo() {
    return {
      localeError: error()
    };
  }
  const index$5 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
    __proto__: null,
    ar,
    az,
    be,
    bg,
    ca,
    cs,
    da,
    de,
    en,
    eo,
    es,
    fa,
    fi,
    fr,
    frCA,
    he,
    hu,
    id: id$1,
    is,
    it,
    ja,
    ka,
    kh,
    km,
    ko,
    lt,
    mk,
    ms,
    nl,
    no,
    ota,
    pl,
    ps,
    pt,
    ru,
    sl,
    sv,
    ta,
    th,
    tr,
    ua,
    uk,
    ur,
    vi,
    yo,
    zhCN,
    zhTW
  }, Symbol.toStringTag, { value: "Module" }));
  var _a;
  const $output = /* @__PURE__ */ Symbol("ZodOutput");
  const $input = /* @__PURE__ */ Symbol("ZodInput");
  class $ZodRegistry {
    constructor() {
      this._map = /* @__PURE__ */ new WeakMap();
      this._idmap = /* @__PURE__ */ new Map();
    }
    add(schema, ..._meta) {
      const meta2 = _meta[0];
      this._map.set(schema, meta2);
      if (meta2 && typeof meta2 === "object" && "id" in meta2) {
        if (this._idmap.has(meta2.id)) {
          throw new Error(`ID ${meta2.id} already exists in the registry`);
        }
        this._idmap.set(meta2.id, schema);
      }
      return this;
    }
    clear() {
      this._map = /* @__PURE__ */ new WeakMap();
      this._idmap = /* @__PURE__ */ new Map();
      return this;
    }
    remove(schema) {
      const meta2 = this._map.get(schema);
      if (meta2 && typeof meta2 === "object" && "id" in meta2) {
        this._idmap.delete(meta2.id);
      }
      this._map.delete(schema);
      return this;
    }
    get(schema) {
      var _a3;
      const p = schema._zod.parent;
      if (p) {
        const pm = __spreadValues({}, (_a3 = this.get(p)) != null ? _a3 : {});
        delete pm.id;
        const f = __spreadValues(__spreadValues({}, pm), this._map.get(schema));
        return Object.keys(f).length ? f : void 0;
      }
      return this._map.get(schema);
    }
    has(schema) {
      return this._map.has(schema);
    }
  }
  function registry() {
    return new $ZodRegistry();
  }
  (_c = (_a = globalThis).__zod_globalRegistry) != null ? _c : _a.__zod_globalRegistry = registry();
  const globalRegistry = globalThis.__zod_globalRegistry;
  function _string(Class2, params) {
    return new Class2(__spreadValues({
      type: "string"
    }, normalizeParams(params)));
  }
  function _coercedString(Class2, params) {
    return new Class2(__spreadValues({
      type: "string",
      coerce: true
    }, normalizeParams(params)));
  }
  function _email(Class2, params) {
    return new Class2(__spreadValues({
      type: "string",
      format: "email",
      check: "string_format",
      abort: false
    }, normalizeParams(params)));
  }
  function _guid(Class2, params) {
    return new Class2(__spreadValues({
      type: "string",
      format: "guid",
      check: "string_format",
      abort: false
    }, normalizeParams(params)));
  }
  function _uuid(Class2, params) {
    return new Class2(__spreadValues({
      type: "string",
      format: "uuid",
      check: "string_format",
      abort: false
    }, normalizeParams(params)));
  }
  function _uuidv4(Class2, params) {
    return new Class2(__spreadValues({
      type: "string",
      format: "uuid",
      check: "string_format",
      abort: false,
      version: "v4"
    }, normalizeParams(params)));
  }
  function _uuidv6(Class2, params) {
    return new Class2(__spreadValues({
      type: "string",
      format: "uuid",
      check: "string_format",
      abort: false,
      version: "v6"
    }, normalizeParams(params)));
  }
  function _uuidv7(Class2, params) {
    return new Class2(__spreadValues({
      type: "string",
      format: "uuid",
      check: "string_format",
      abort: false,
      version: "v7"
    }, normalizeParams(params)));
  }
  function _url(Class2, params) {
    return new Class2(__spreadValues({
      type: "string",
      format: "url",
      check: "string_format",
      abort: false
    }, normalizeParams(params)));
  }
  function _emoji(Class2, params) {
    return new Class2(__spreadValues({
      type: "string",
      format: "emoji",
      check: "string_format",
      abort: false
    }, normalizeParams(params)));
  }
  function _nanoid(Class2, params) {
    return new Class2(__spreadValues({
      type: "string",
      format: "nanoid",
      check: "string_format",
      abort: false
    }, normalizeParams(params)));
  }
  function _cuid(Class2, params) {
    return new Class2(__spreadValues({
      type: "string",
      format: "cuid",
      check: "string_format",
      abort: false
    }, normalizeParams(params)));
  }
  function _cuid2(Class2, params) {
    return new Class2(__spreadValues({
      type: "string",
      format: "cuid2",
      check: "string_format",
      abort: false
    }, normalizeParams(params)));
  }
  function _ulid(Class2, params) {
    return new Class2(__spreadValues({
      type: "string",
      format: "ulid",
      check: "string_format",
      abort: false
    }, normalizeParams(params)));
  }
  function _xid(Class2, params) {
    return new Class2(__spreadValues({
      type: "string",
      format: "xid",
      check: "string_format",
      abort: false
    }, normalizeParams(params)));
  }
  function _ksuid(Class2, params) {
    return new Class2(__spreadValues({
      type: "string",
      format: "ksuid",
      check: "string_format",
      abort: false
    }, normalizeParams(params)));
  }
  function _ipv4(Class2, params) {
    return new Class2(__spreadValues({
      type: "string",
      format: "ipv4",
      check: "string_format",
      abort: false
    }, normalizeParams(params)));
  }
  function _ipv6(Class2, params) {
    return new Class2(__spreadValues({
      type: "string",
      format: "ipv6",
      check: "string_format",
      abort: false
    }, normalizeParams(params)));
  }
  function _mac(Class2, params) {
    return new Class2(__spreadValues({
      type: "string",
      format: "mac",
      check: "string_format",
      abort: false
    }, normalizeParams(params)));
  }
  function _cidrv4(Class2, params) {
    return new Class2(__spreadValues({
      type: "string",
      format: "cidrv4",
      check: "string_format",
      abort: false
    }, normalizeParams(params)));
  }
  function _cidrv6(Class2, params) {
    return new Class2(__spreadValues({
      type: "string",
      format: "cidrv6",
      check: "string_format",
      abort: false
    }, normalizeParams(params)));
  }
  function _base64(Class2, params) {
    return new Class2(__spreadValues({
      type: "string",
      format: "base64",
      check: "string_format",
      abort: false
    }, normalizeParams(params)));
  }
  function _base64url(Class2, params) {
    return new Class2(__spreadValues({
      type: "string",
      format: "base64url",
      check: "string_format",
      abort: false
    }, normalizeParams(params)));
  }
  function _e164(Class2, params) {
    return new Class2(__spreadValues({
      type: "string",
      format: "e164",
      check: "string_format",
      abort: false
    }, normalizeParams(params)));
  }
  function _jwt(Class2, params) {
    return new Class2(__spreadValues({
      type: "string",
      format: "jwt",
      check: "string_format",
      abort: false
    }, normalizeParams(params)));
  }
  const TimePrecision = {
    Any: null,
    Minute: -1,
    Second: 0,
    Millisecond: 3,
    Microsecond: 6
  };
  function _isoDateTime(Class2, params) {
    return new Class2(__spreadValues({
      type: "string",
      format: "datetime",
      check: "string_format",
      offset: false,
      local: false,
      precision: null
    }, normalizeParams(params)));
  }
  function _isoDate(Class2, params) {
    return new Class2(__spreadValues({
      type: "string",
      format: "date",
      check: "string_format"
    }, normalizeParams(params)));
  }
  function _isoTime(Class2, params) {
    return new Class2(__spreadValues({
      type: "string",
      format: "time",
      check: "string_format",
      precision: null
    }, normalizeParams(params)));
  }
  function _isoDuration(Class2, params) {
    return new Class2(__spreadValues({
      type: "string",
      format: "duration",
      check: "string_format"
    }, normalizeParams(params)));
  }
  function _number(Class2, params) {
    return new Class2(__spreadValues({
      type: "number",
      checks: []
    }, normalizeParams(params)));
  }
  function _coercedNumber(Class2, params) {
    return new Class2(__spreadValues({
      type: "number",
      coerce: true,
      checks: []
    }, normalizeParams(params)));
  }
  function _int(Class2, params) {
    return new Class2(__spreadValues({
      type: "number",
      check: "number_format",
      abort: false,
      format: "safeint"
    }, normalizeParams(params)));
  }
  function _float32(Class2, params) {
    return new Class2(__spreadValues({
      type: "number",
      check: "number_format",
      abort: false,
      format: "float32"
    }, normalizeParams(params)));
  }
  function _float64(Class2, params) {
    return new Class2(__spreadValues({
      type: "number",
      check: "number_format",
      abort: false,
      format: "float64"
    }, normalizeParams(params)));
  }
  function _int32(Class2, params) {
    return new Class2(__spreadValues({
      type: "number",
      check: "number_format",
      abort: false,
      format: "int32"
    }, normalizeParams(params)));
  }
  function _uint32(Class2, params) {
    return new Class2(__spreadValues({
      type: "number",
      check: "number_format",
      abort: false,
      format: "uint32"
    }, normalizeParams(params)));
  }
  function _boolean(Class2, params) {
    return new Class2(__spreadValues({
      type: "boolean"
    }, normalizeParams(params)));
  }
  function _coercedBoolean(Class2, params) {
    return new Class2(__spreadValues({
      type: "boolean",
      coerce: true
    }, normalizeParams(params)));
  }
  function _bigint(Class2, params) {
    return new Class2(__spreadValues({
      type: "bigint"
    }, normalizeParams(params)));
  }
  function _coercedBigint(Class2, params) {
    return new Class2(__spreadValues({
      type: "bigint",
      coerce: true
    }, normalizeParams(params)));
  }
  function _int64(Class2, params) {
    return new Class2(__spreadValues({
      type: "bigint",
      check: "bigint_format",
      abort: false,
      format: "int64"
    }, normalizeParams(params)));
  }
  function _uint64(Class2, params) {
    return new Class2(__spreadValues({
      type: "bigint",
      check: "bigint_format",
      abort: false,
      format: "uint64"
    }, normalizeParams(params)));
  }
  function _symbol(Class2, params) {
    return new Class2(__spreadValues({
      type: "symbol"
    }, normalizeParams(params)));
  }
  function _undefined$1(Class2, params) {
    return new Class2(__spreadValues({
      type: "undefined"
    }, normalizeParams(params)));
  }
  function _null$1(Class2, params) {
    return new Class2(__spreadValues({
      type: "null"
    }, normalizeParams(params)));
  }
  function _any(Class2) {
    return new Class2({
      type: "any"
    });
  }
  function _unknown(Class2) {
    return new Class2({
      type: "unknown"
    });
  }
  function _never(Class2, params) {
    return new Class2(__spreadValues({
      type: "never"
    }, normalizeParams(params)));
  }
  function _void$1(Class2, params) {
    return new Class2(__spreadValues({
      type: "void"
    }, normalizeParams(params)));
  }
  function _date(Class2, params) {
    return new Class2(__spreadValues({
      type: "date"
    }, normalizeParams(params)));
  }
  function _coercedDate(Class2, params) {
    return new Class2(__spreadValues({
      type: "date",
      coerce: true
    }, normalizeParams(params)));
  }
  function _nan(Class2, params) {
    return new Class2(__spreadValues({
      type: "nan"
    }, normalizeParams(params)));
  }
  function _lt(value, params) {
    return new $ZodCheckLessThan(__spreadProps(__spreadValues({
      check: "less_than"
    }, normalizeParams(params)), {
      value,
      inclusive: false
    }));
  }
  function _lte(value, params) {
    return new $ZodCheckLessThan(__spreadProps(__spreadValues({
      check: "less_than"
    }, normalizeParams(params)), {
      value,
      inclusive: true
    }));
  }
  function _gt(value, params) {
    return new $ZodCheckGreaterThan(__spreadProps(__spreadValues({
      check: "greater_than"
    }, normalizeParams(params)), {
      value,
      inclusive: false
    }));
  }
  function _gte(value, params) {
    return new $ZodCheckGreaterThan(__spreadProps(__spreadValues({
      check: "greater_than"
    }, normalizeParams(params)), {
      value,
      inclusive: true
    }));
  }
  function _positive(params) {
    return _gt(0, params);
  }
  function _negative(params) {
    return _lt(0, params);
  }
  function _nonpositive(params) {
    return _lte(0, params);
  }
  function _nonnegative(params) {
    return _gte(0, params);
  }
  function _multipleOf(value, params) {
    return new $ZodCheckMultipleOf(__spreadProps(__spreadValues({
      check: "multiple_of"
    }, normalizeParams(params)), {
      value
    }));
  }
  function _maxSize(maximum, params) {
    return new $ZodCheckMaxSize(__spreadProps(__spreadValues({
      check: "max_size"
    }, normalizeParams(params)), {
      maximum
    }));
  }
  function _minSize(minimum, params) {
    return new $ZodCheckMinSize(__spreadProps(__spreadValues({
      check: "min_size"
    }, normalizeParams(params)), {
      minimum
    }));
  }
  function _size(size, params) {
    return new $ZodCheckSizeEquals(__spreadProps(__spreadValues({
      check: "size_equals"
    }, normalizeParams(params)), {
      size
    }));
  }
  function _maxLength(maximum, params) {
    const ch = new $ZodCheckMaxLength(__spreadProps(__spreadValues({
      check: "max_length"
    }, normalizeParams(params)), {
      maximum
    }));
    return ch;
  }
  function _minLength(minimum, params) {
    return new $ZodCheckMinLength(__spreadProps(__spreadValues({
      check: "min_length"
    }, normalizeParams(params)), {
      minimum
    }));
  }
  function _length(length, params) {
    return new $ZodCheckLengthEquals(__spreadProps(__spreadValues({
      check: "length_equals"
    }, normalizeParams(params)), {
      length
    }));
  }
  function _regex(pattern2, params) {
    return new $ZodCheckRegex(__spreadProps(__spreadValues({
      check: "string_format",
      format: "regex"
    }, normalizeParams(params)), {
      pattern: pattern2
    }));
  }
  function _lowercase(params) {
    return new $ZodCheckLowerCase(__spreadValues({
      check: "string_format",
      format: "lowercase"
    }, normalizeParams(params)));
  }
  function _uppercase(params) {
    return new $ZodCheckUpperCase(__spreadValues({
      check: "string_format",
      format: "uppercase"
    }, normalizeParams(params)));
  }
  function _includes(includes, params) {
    return new $ZodCheckIncludes(__spreadProps(__spreadValues({
      check: "string_format",
      format: "includes"
    }, normalizeParams(params)), {
      includes
    }));
  }
  function _startsWith(prefix, params) {
    return new $ZodCheckStartsWith(__spreadProps(__spreadValues({
      check: "string_format",
      format: "starts_with"
    }, normalizeParams(params)), {
      prefix
    }));
  }
  function _endsWith(suffix, params) {
    return new $ZodCheckEndsWith(__spreadProps(__spreadValues({
      check: "string_format",
      format: "ends_with"
    }, normalizeParams(params)), {
      suffix
    }));
  }
  function _property(property, schema, params) {
    return new $ZodCheckProperty(__spreadValues({
      check: "property",
      property,
      schema
    }, normalizeParams(params)));
  }
  function _mime(types2, params) {
    return new $ZodCheckMimeType(__spreadValues({
      check: "mime_type",
      mime: types2
    }, normalizeParams(params)));
  }
  function _overwrite(tx) {
    return new $ZodCheckOverwrite({
      check: "overwrite",
      tx
    });
  }
  function _normalize(form) {
    return _overwrite((input) => input.normalize(form));
  }
  function _trim() {
    return _overwrite((input) => input.trim());
  }
  function _toLowerCase() {
    return _overwrite((input) => input.toLowerCase());
  }
  function _toUpperCase() {
    return _overwrite((input) => input.toUpperCase());
  }
  function _slugify() {
    return _overwrite((input) => slugify(input));
  }
  function _array(Class2, element, params) {
    return new Class2(__spreadValues({
      type: "array",
      element
    }, normalizeParams(params)));
  }
  function _union(Class2, options, params) {
    return new Class2(__spreadValues({
      type: "union",
      options
    }, normalizeParams(params)));
  }
  function _xor(Class2, options, params) {
    return new Class2(__spreadValues({
      type: "union",
      options,
      inclusive: false
    }, normalizeParams(params)));
  }
  function _discriminatedUnion(Class2, discriminator2, options, params) {
    return new Class2(__spreadValues({
      type: "union",
      options,
      discriminator: discriminator2
    }, normalizeParams(params)));
  }
  function _intersection(Class2, left, right) {
    return new Class2({
      type: "intersection",
      left,
      right
    });
  }
  function _tuple(Class2, items2, _paramsOrRest, _params) {
    const hasRest = _paramsOrRest instanceof $ZodType;
    const params = hasRest ? _params : _paramsOrRest;
    const rest = hasRest ? _paramsOrRest : null;
    return new Class2(__spreadValues({
      type: "tuple",
      items: items2,
      rest
    }, normalizeParams(params)));
  }
  function _record(Class2, keyType, valueType, params) {
    return new Class2(__spreadValues({
      type: "record",
      keyType,
      valueType
    }, normalizeParams(params)));
  }
  function _map(Class2, keyType, valueType, params) {
    return new Class2(__spreadValues({
      type: "map",
      keyType,
      valueType
    }, normalizeParams(params)));
  }
  function _set(Class2, valueType, params) {
    return new Class2(__spreadValues({
      type: "set",
      valueType
    }, normalizeParams(params)));
  }
  function _enum$2(Class2, values, params) {
    const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;
    return new Class2(__spreadValues({
      type: "enum",
      entries
    }, normalizeParams(params)));
  }
  function _nativeEnum(Class2, entries, params) {
    return new Class2(__spreadValues({
      type: "enum",
      entries
    }, normalizeParams(params)));
  }
  function _literal(Class2, value, params) {
    return new Class2(__spreadValues({
      type: "literal",
      values: Array.isArray(value) ? value : [value]
    }, normalizeParams(params)));
  }
  function _file(Class2, params) {
    return new Class2(__spreadValues({
      type: "file"
    }, normalizeParams(params)));
  }
  function _transform(Class2, fn) {
    return new Class2({
      type: "transform",
      transform: fn
    });
  }
  function _optional(Class2, innerType) {
    return new Class2({
      type: "optional",
      innerType
    });
  }
  function _nullable(Class2, innerType) {
    return new Class2({
      type: "nullable",
      innerType
    });
  }
  function _default$1(Class2, innerType, defaultValue) {
    return new Class2({
      type: "default",
      innerType,
      get defaultValue() {
        return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
      }
    });
  }
  function _nonoptional(Class2, innerType, params) {
    return new Class2(__spreadValues({
      type: "nonoptional",
      innerType
    }, normalizeParams(params)));
  }
  function _success(Class2, innerType) {
    return new Class2({
      type: "success",
      innerType
    });
  }
  function _catch$1(Class2, innerType, catchValue) {
    return new Class2({
      type: "catch",
      innerType,
      catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
    });
  }
  function _pipe(Class2, in_, out) {
    return new Class2({
      type: "pipe",
      in: in_,
      out
    });
  }
  function _readonly(Class2, innerType) {
    return new Class2({
      type: "readonly",
      innerType
    });
  }
  function _templateLiteral(Class2, parts, params) {
    return new Class2(__spreadValues({
      type: "template_literal",
      parts
    }, normalizeParams(params)));
  }
  function _lazy(Class2, getter) {
    return new Class2({
      type: "lazy",
      getter
    });
  }
  function _promise(Class2, innerType) {
    return new Class2({
      type: "promise",
      innerType
    });
  }
  function _custom(Class2, fn, _params) {
    var _a3;
    const norm = normalizeParams(_params);
    (_a3 = norm.abort) != null ? _a3 : norm.abort = true;
    const schema = new Class2(__spreadValues({
      type: "custom",
      check: "custom",
      fn
    }, norm));
    return schema;
  }
  function _refine(Class2, fn, _params) {
    const schema = new Class2(__spreadValues({
      type: "custom",
      check: "custom",
      fn
    }, normalizeParams(_params)));
    return schema;
  }
  function _superRefine(fn) {
    const ch = _check((payload) => {
      payload.addIssue = (issue$1) => {
        var _a3, _b2, _c2, _d2;
        if (typeof issue$1 === "string") {
          payload.issues.push(issue(issue$1, payload.value, ch._zod.def));
        } else {
          const _issue = issue$1;
          if (_issue.fatal)
            _issue.continue = false;
          (_a3 = _issue.code) != null ? _a3 : _issue.code = "custom";
          (_b2 = _issue.input) != null ? _b2 : _issue.input = payload.value;
          (_c2 = _issue.inst) != null ? _c2 : _issue.inst = ch;
          (_d2 = _issue.continue) != null ? _d2 : _issue.continue = !ch._zod.def.abort;
          payload.issues.push(issue(_issue));
        }
      };
      return fn(payload.value, payload);
    });
    return ch;
  }
  function _check(fn, params) {
    const ch = new $ZodCheck(__spreadValues({
      check: "custom"
    }, normalizeParams(params)));
    ch._zod.check = fn;
    return ch;
  }
  function describe$1(description2) {
    const ch = new $ZodCheck({ check: "describe" });
    ch._zod.onattach = [
      (inst) => {
        var _a3;
        const existing = (_a3 = globalRegistry.get(inst)) != null ? _a3 : {};
        globalRegistry.add(inst, __spreadProps(__spreadValues({}, existing), { description: description2 }));
      }
    ];
    ch._zod.check = () => {
    };
    return ch;
  }
  function meta$1(metadata2) {
    const ch = new $ZodCheck({ check: "meta" });
    ch._zod.onattach = [
      (inst) => {
        var _a3;
        const existing = (_a3 = globalRegistry.get(inst)) != null ? _a3 : {};
        globalRegistry.add(inst, __spreadValues(__spreadValues({}, existing), metadata2));
      }
    ];
    ch._zod.check = () => {
    };
    return ch;
  }
  function _stringbool(Classes, _params) {
    var _a3, _b2, _c2, _d2, _e;
    const params = normalizeParams(_params);
    let truthyArray = (_a3 = params.truthy) != null ? _a3 : ["true", "1", "yes", "on", "y", "enabled"];
    let falsyArray = (_b2 = params.falsy) != null ? _b2 : ["false", "0", "no", "off", "n", "disabled"];
    if (params.case !== "sensitive") {
      truthyArray = truthyArray.map((v) => typeof v === "string" ? v.toLowerCase() : v);
      falsyArray = falsyArray.map((v) => typeof v === "string" ? v.toLowerCase() : v);
    }
    const truthySet = new Set(truthyArray);
    const falsySet = new Set(falsyArray);
    const _Codec = (_c2 = Classes.Codec) != null ? _c2 : $ZodCodec;
    const _Boolean = (_d2 = Classes.Boolean) != null ? _d2 : $ZodBoolean;
    const _String = (_e = Classes.String) != null ? _e : $ZodString;
    const stringSchema = new _String({ type: "string", error: params.error });
    const booleanSchema = new _Boolean({ type: "boolean", error: params.error });
    const codec2 = new _Codec({
      type: "pipe",
      in: stringSchema,
      out: booleanSchema,
      transform: ((input, payload) => {
        let data = input;
        if (params.case !== "sensitive")
          data = data.toLowerCase();
        if (truthySet.has(data)) {
          return true;
        } else if (falsySet.has(data)) {
          return false;
        } else {
          payload.issues.push({
            code: "invalid_value",
            expected: "stringbool",
            values: [...truthySet, ...falsySet],
            input: payload.value,
            inst: codec2,
            continue: false
          });
          return {};
        }
      }),
      reverseTransform: ((input, _payload) => {
        if (input === true) {
          return truthyArray[0] || "true";
        } else {
          return falsyArray[0] || "false";
        }
      }),
      error: params.error
    });
    return codec2;
  }
  function _stringFormat(Class2, format2, fnOrRegex, _params = {}) {
    const params = normalizeParams(_params);
    const def = __spreadValues(__spreadProps(__spreadValues({}, normalizeParams(_params)), {
      check: "string_format",
      type: "string",
      format: format2,
      fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val)
    }), params);
    if (fnOrRegex instanceof RegExp) {
      def.pattern = fnOrRegex;
    }
    const inst = new Class2(def);
    return inst;
  }
  function initializeContext(params) {
    var _a3, _b2, _c2, _d2, _e, _f, _g, _h, _i;
    let target = (_a3 = params == null ? void 0 : params.target) != null ? _a3 : "draft-2020-12";
    if (target === "draft-4")
      target = "draft-04";
    if (target === "draft-7")
      target = "draft-07";
    return {
      processors: (_b2 = params.processors) != null ? _b2 : {},
      metadataRegistry: (_c2 = params == null ? void 0 : params.metadata) != null ? _c2 : globalRegistry,
      target,
      unrepresentable: (_d2 = params == null ? void 0 : params.unrepresentable) != null ? _d2 : "throw",
      override: (_e = params == null ? void 0 : params.override) != null ? _e : (() => {
      }),
      io: (_f = params == null ? void 0 : params.io) != null ? _f : "output",
      counter: 0,
      seen: /* @__PURE__ */ new Map(),
      cycles: (_g = params == null ? void 0 : params.cycles) != null ? _g : "ref",
      reused: (_h = params == null ? void 0 : params.reused) != null ? _h : "inline",
      external: (_i = params == null ? void 0 : params.external) != null ? _i : void 0
    };
  }
  function process$2(schema, ctx, _params = { path: [], schemaPath: [] }) {
    var _a4, _b2, _c2;
    var _a3;
    const def = schema._zod.def;
    const seen = ctx.seen.get(schema);
    if (seen) {
      seen.count++;
      const isCycle = _params.schemaPath.includes(schema);
      if (isCycle) {
        seen.cycle = _params.path;
      }
      return seen.schema;
    }
    const result2 = { schema: {}, count: 1, cycle: void 0, path: _params.path };
    ctx.seen.set(schema, result2);
    const overrideSchema = (_b2 = (_a4 = schema._zod).toJSONSchema) == null ? void 0 : _b2.call(_a4);
    if (overrideSchema) {
      result2.schema = overrideSchema;
    } else {
      const params = __spreadProps(__spreadValues({}, _params), {
        schemaPath: [..._params.schemaPath, schema],
        path: _params.path
      });
      const parent = schema._zod.parent;
      if (parent) {
        result2.ref = parent;
        process$2(parent, ctx, params);
        ctx.seen.get(parent).isParent = true;
      } else if (schema._zod.processJSONSchema) {
        schema._zod.processJSONSchema(ctx, result2.schema, params);
      } else {
        const _json = result2.schema;
        const processor = ctx.processors[def.type];
        if (!processor) {
          throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);
        }
        processor(schema, ctx, _json, params);
      }
    }
    const meta2 = ctx.metadataRegistry.get(schema);
    if (meta2)
      Object.assign(result2.schema, meta2);
    if (ctx.io === "input" && isTransforming(schema)) {
      delete result2.schema.examples;
      delete result2.schema.default;
    }
    if (ctx.io === "input" && result2.schema._prefault)
      (_c2 = (_a3 = result2.schema).default) != null ? _c2 : _a3.default = result2.schema._prefault;
    delete result2.schema._prefault;
    const _result = ctx.seen.get(schema);
    return _result.schema;
  }
  function extractDefs(ctx, schema) {
    var _a3, _b2, _c2;
    const root = ctx.seen.get(schema);
    if (!root)
      throw new Error("Unprocessed schema. This is a bug in Zod.");
    const makeURI = (entry) => {
      var _a4, _b3, _c3, _d2, _e;
      const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions";
      if (ctx.external) {
        const externalId = (_a4 = ctx.external.registry.get(entry[0])) == null ? void 0 : _a4.id;
        const uriGenerator = (_b3 = ctx.external.uri) != null ? _b3 : ((id3) => id3);
        if (externalId) {
          return { ref: uriGenerator(externalId) };
        }
        const id2 = (_d2 = (_c3 = entry[1].defId) != null ? _c3 : entry[1].schema.id) != null ? _d2 : `schema${ctx.counter++}`;
        entry[1].defId = id2;
        return { defId: id2, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id2}` };
      }
      if (entry[1] === root) {
        return { ref: "#" };
      }
      const uriPrefix = `#`;
      const defUriPrefix = `${uriPrefix}/${defsSegment}/`;
      const defId = (_e = entry[1].schema.id) != null ? _e : `__schema${ctx.counter++}`;
      return { defId, ref: defUriPrefix + defId };
    };
    const extractToDef = (entry) => {
      if (entry[1].schema.$ref) {
        return;
      }
      const seen = entry[1];
      const { ref: ref2, defId } = makeURI(entry);
      seen.def = __spreadValues({}, seen.schema);
      if (defId)
        seen.defId = defId;
      const schema2 = seen.schema;
      for (const key in schema2) {
        delete schema2[key];
      }
      schema2.$ref = ref2;
    };
    if (ctx.cycles === "throw") {
      for (const entry of ctx.seen.entries()) {
        const seen = entry[1];
        if (seen.cycle) {
          throw new Error(`Cycle detected: #/${(_a3 = seen.cycle) == null ? void 0 : _a3.join("/")}/<root>

Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`);
        }
      }
    }
    for (const entry of ctx.seen.entries()) {
      const seen = entry[1];
      if (schema === entry[0]) {
        extractToDef(entry);
        continue;
      }
      if (ctx.external) {
        const ext = (_b2 = ctx.external.registry.get(entry[0])) == null ? void 0 : _b2.id;
        if (schema !== entry[0] && ext) {
          extractToDef(entry);
          continue;
        }
      }
      const id2 = (_c2 = ctx.metadataRegistry.get(entry[0])) == null ? void 0 : _c2.id;
      if (id2) {
        extractToDef(entry);
        continue;
      }
      if (seen.cycle) {
        extractToDef(entry);
        continue;
      }
      if (seen.count > 1) {
        if (ctx.reused === "ref") {
          extractToDef(entry);
          continue;
        }
      }
    }
  }
  function finalize(ctx, schema) {
    var _a3, _b2, _c2, _d2, _e;
    const root = ctx.seen.get(schema);
    if (!root)
      throw new Error("Unprocessed schema. This is a bug in Zod.");
    const flattenRef = (zodSchema) => {
      var _a4, _b3, _c3;
      const seen = ctx.seen.get(zodSchema);
      const schema2 = (_a4 = seen.def) != null ? _a4 : seen.schema;
      const _cached = __spreadValues({}, schema2);
      if (seen.ref === null) {
        return;
      }
      const ref2 = seen.ref;
      seen.ref = null;
      if (ref2) {
        flattenRef(ref2);
        const refSchema = ctx.seen.get(ref2).schema;
        if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) {
          schema2.allOf = (_b3 = schema2.allOf) != null ? _b3 : [];
          schema2.allOf.push(refSchema);
        } else {
          Object.assign(schema2, refSchema);
          Object.assign(schema2, _cached);
        }
      }
      if (!seen.isParent)
        ctx.override({
          zodSchema,
          jsonSchema: schema2,
          path: (_c3 = seen.path) != null ? _c3 : []
        });
    };
    for (const entry of [...ctx.seen.entries()].reverse()) {
      flattenRef(entry[0]);
    }
    const result2 = {};
    if (ctx.target === "draft-2020-12") {
      result2.$schema = "https://json-schema.org/draft/2020-12/schema";
    } else if (ctx.target === "draft-07") {
      result2.$schema = "http://json-schema.org/draft-07/schema#";
    } else if (ctx.target === "draft-04") {
      result2.$schema = "http://json-schema.org/draft-04/schema#";
    } else if (ctx.target === "openapi-3.0") ;
    else ;
    if ((_a3 = ctx.external) == null ? void 0 : _a3.uri) {
      const id2 = (_b2 = ctx.external.registry.get(schema)) == null ? void 0 : _b2.id;
      if (!id2)
        throw new Error("Schema is missing an `id` property");
      result2.$id = ctx.external.uri(id2);
    }
    Object.assign(result2, (_c2 = root.def) != null ? _c2 : root.schema);
    const defs = (_e = (_d2 = ctx.external) == null ? void 0 : _d2.defs) != null ? _e : {};
    for (const entry of ctx.seen.entries()) {
      const seen = entry[1];
      if (seen.def && seen.defId) {
        defs[seen.defId] = seen.def;
      }
    }
    if (ctx.external) ;
    else {
      if (Object.keys(defs).length > 0) {
        if (ctx.target === "draft-2020-12") {
          result2.$defs = defs;
        } else {
          result2.definitions = defs;
        }
      }
    }
    try {
      const finalized = JSON.parse(JSON.stringify(result2));
      Object.defineProperty(finalized, "~standard", {
        value: __spreadProps(__spreadValues({}, schema["~standard"]), {
          jsonSchema: {
            input: createStandardJSONSchemaMethod(schema, "input"),
            output: createStandardJSONSchemaMethod(schema, "output")
          }
        }),
        enumerable: false,
        writable: false
      });
      return finalized;
    } catch (_err) {
      throw new Error("Error converting schema to JSON.");
    }
  }
  function isTransforming(_schema, _ctx) {
    const ctx = _ctx != null ? _ctx : { seen: /* @__PURE__ */ new Set() };
    if (ctx.seen.has(_schema))
      return false;
    ctx.seen.add(_schema);
    const def = _schema._zod.def;
    if (def.type === "transform")
      return true;
    if (def.type === "array")
      return isTransforming(def.element, ctx);
    if (def.type === "set")
      return isTransforming(def.valueType, ctx);
    if (def.type === "lazy")
      return isTransforming(def.getter(), ctx);
    if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault") {
      return isTransforming(def.innerType, ctx);
    }
    if (def.type === "intersection") {
      return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);
    }
    if (def.type === "record" || def.type === "map") {
      return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);
    }
    if (def.type === "pipe") {
      return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);
    }
    if (def.type === "object") {
      for (const key in def.shape) {
        if (isTransforming(def.shape[key], ctx))
          return true;
      }
      return false;
    }
    if (def.type === "union") {
      for (const option of def.options) {
        if (isTransforming(option, ctx))
          return true;
      }
      return false;
    }
    if (def.type === "tuple") {
      for (const item of def.items) {
        if (isTransforming(item, ctx))
          return true;
      }
      if (def.rest && isTransforming(def.rest, ctx))
        return true;
      return false;
    }
    return false;
  }
  const createToJSONSchemaMethod = (schema, processors = {}) => (params) => {
    const ctx = initializeContext(__spreadProps(__spreadValues({}, params), { processors }));
    process$2(schema, ctx);
    extractDefs(ctx, schema);
    return finalize(ctx, schema);
  };
  const createStandardJSONSchemaMethod = (schema, io) => (params) => {
    const { libraryOptions, target } = params != null ? params : {};
    const ctx = initializeContext(__spreadProps(__spreadValues({}, libraryOptions != null ? libraryOptions : {}), { target, io, processors: {} }));
    process$2(schema, ctx);
    extractDefs(ctx, schema);
    return finalize(ctx, schema);
  };
  const formatMap = {
    guid: "uuid",
    url: "uri",
    datetime: "date-time",
    json_string: "json-string",
    regex: ""
    // do not set
  };
  const stringProcessor = (schema, ctx, _json, _params) => {
    var _a3;
    const json2 = _json;
    json2.type = "string";
    const { minimum, maximum, format: format2, patterns, contentEncoding } = schema._zod.bag;
    if (typeof minimum === "number")
      json2.minLength = minimum;
    if (typeof maximum === "number")
      json2.maxLength = maximum;
    if (format2) {
      json2.format = (_a3 = formatMap[format2]) != null ? _a3 : format2;
      if (json2.format === "")
        delete json2.format;
    }
    if (contentEncoding)
      json2.contentEncoding = contentEncoding;
    if (patterns && patterns.size > 0) {
      const regexes2 = [...patterns];
      if (regexes2.length === 1)
        json2.pattern = regexes2[0].source;
      else if (regexes2.length > 1) {
        json2.allOf = [
          ...regexes2.map((regex) => __spreadProps(__spreadValues({}, ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {}), {
            pattern: regex.source
          }))
        ];
      }
    }
  };
  const numberProcessor = (schema, ctx, _json, _params) => {
    const json2 = _json;
    const { minimum, maximum, format: format2, multipleOf: multipleOf2, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;
    if (typeof format2 === "string" && format2.includes("int"))
      json2.type = "integer";
    else
      json2.type = "number";
    if (typeof exclusiveMinimum === "number") {
      if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
        json2.minimum = exclusiveMinimum;
        json2.exclusiveMinimum = true;
      } else {
        json2.exclusiveMinimum = exclusiveMinimum;
      }
    }
    if (typeof minimum === "number") {
      json2.minimum = minimum;
      if (typeof exclusiveMinimum === "number" && ctx.target !== "draft-04") {
        if (exclusiveMinimum >= minimum)
          delete json2.minimum;
        else
          delete json2.exclusiveMinimum;
      }
    }
    if (typeof exclusiveMaximum === "number") {
      if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
        json2.maximum = exclusiveMaximum;
        json2.exclusiveMaximum = true;
      } else {
        json2.exclusiveMaximum = exclusiveMaximum;
      }
    }
    if (typeof maximum === "number") {
      json2.maximum = maximum;
      if (typeof exclusiveMaximum === "number" && ctx.target !== "draft-04") {
        if (exclusiveMaximum <= maximum)
          delete json2.maximum;
        else
          delete json2.exclusiveMaximum;
      }
    }
    if (typeof multipleOf2 === "number")
      json2.multipleOf = multipleOf2;
  };
  const booleanProcessor = (_schema, _ctx, json2, _params) => {
    json2.type = "boolean";
  };
  const bigintProcessor = (_schema, ctx, _json, _params) => {
    if (ctx.unrepresentable === "throw") {
      throw new Error("BigInt cannot be represented in JSON Schema");
    }
  };
  const symbolProcessor = (_schema, ctx, _json, _params) => {
    if (ctx.unrepresentable === "throw") {
      throw new Error("Symbols cannot be represented in JSON Schema");
    }
  };
  const nullProcessor = (_schema, ctx, json2, _params) => {
    if (ctx.target === "openapi-3.0") {
      json2.type = "string";
      json2.nullable = true;
      json2.enum = [null];
    } else {
      json2.type = "null";
    }
  };
  const undefinedProcessor = (_schema, ctx, _json, _params) => {
    if (ctx.unrepresentable === "throw") {
      throw new Error("Undefined cannot be represented in JSON Schema");
    }
  };
  const voidProcessor = (_schema, ctx, _json, _params) => {
    if (ctx.unrepresentable === "throw") {
      throw new Error("Void cannot be represented in JSON Schema");
    }
  };
  const neverProcessor = (_schema, _ctx, json2, _params) => {
    json2.not = {};
  };
  const anyProcessor = (_schema, _ctx, _json, _params) => {
  };
  const unknownProcessor = (_schema, _ctx, _json, _params) => {
  };
  const dateProcessor = (_schema, ctx, _json, _params) => {
    if (ctx.unrepresentable === "throw") {
      throw new Error("Date cannot be represented in JSON Schema");
    }
  };
  const enumProcessor = (schema, _ctx, json2, _params) => {
    const def = schema._zod.def;
    const values = getEnumValues(def.entries);
    if (values.every((v) => typeof v === "number"))
      json2.type = "number";
    if (values.every((v) => typeof v === "string"))
      json2.type = "string";
    json2.enum = values;
  };
  const literalProcessor = (schema, ctx, json2, _params) => {
    const def = schema._zod.def;
    const vals = [];
    for (const val of def.values) {
      if (val === void 0) {
        if (ctx.unrepresentable === "throw") {
          throw new Error("Literal `undefined` cannot be represented in JSON Schema");
        }
      } else if (typeof val === "bigint") {
        if (ctx.unrepresentable === "throw") {
          throw new Error("BigInt literals cannot be represented in JSON Schema");
        } else {
          vals.push(Number(val));
        }
      } else {
        vals.push(val);
      }
    }
    if (vals.length === 0) ;
    else if (vals.length === 1) {
      const val = vals[0];
      json2.type = val === null ? "null" : typeof val;
      if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
        json2.enum = [val];
      } else {
        json2.const = val;
      }
    } else {
      if (vals.every((v) => typeof v === "number"))
        json2.type = "number";
      if (vals.every((v) => typeof v === "string"))
        json2.type = "string";
      if (vals.every((v) => typeof v === "boolean"))
        json2.type = "boolean";
      if (vals.every((v) => v === null))
        json2.type = "null";
      json2.enum = vals;
    }
  };
  const nanProcessor = (_schema, ctx, _json, _params) => {
    if (ctx.unrepresentable === "throw") {
      throw new Error("NaN cannot be represented in JSON Schema");
    }
  };
  const templateLiteralProcessor = (schema, _ctx, json2, _params) => {
    const _json = json2;
    const pattern2 = schema._zod.pattern;
    if (!pattern2)
      throw new Error("Pattern not found in template literal");
    _json.type = "string";
    _json.pattern = pattern2.source;
  };
  const fileProcessor = (schema, _ctx, json2, _params) => {
    const _json = json2;
    const file2 = {
      type: "string",
      format: "binary",
      contentEncoding: "binary"
    };
    const { minimum, maximum, mime } = schema._zod.bag;
    if (minimum !== void 0)
      file2.minLength = minimum;
    if (maximum !== void 0)
      file2.maxLength = maximum;
    if (mime) {
      if (mime.length === 1) {
        file2.contentMediaType = mime[0];
        Object.assign(_json, file2);
      } else {
        _json.anyOf = mime.map((m) => {
          const mFile = __spreadProps(__spreadValues({}, file2), { contentMediaType: m });
          return mFile;
        });
      }
    } else {
      Object.assign(_json, file2);
    }
  };
  const successProcessor = (_schema, _ctx, json2, _params) => {
    json2.type = "boolean";
  };
  const customProcessor = (_schema, ctx, _json, _params) => {
    if (ctx.unrepresentable === "throw") {
      throw new Error("Custom types cannot be represented in JSON Schema");
    }
  };
  const functionProcessor = (_schema, ctx, _json, _params) => {
    if (ctx.unrepresentable === "throw") {
      throw new Error("Function types cannot be represented in JSON Schema");
    }
  };
  const transformProcessor = (_schema, ctx, _json, _params) => {
    if (ctx.unrepresentable === "throw") {
      throw new Error("Transforms cannot be represented in JSON Schema");
    }
  };
  const mapProcessor = (_schema, ctx, _json, _params) => {
    if (ctx.unrepresentable === "throw") {
      throw new Error("Map cannot be represented in JSON Schema");
    }
  };
  const setProcessor = (_schema, ctx, _json, _params) => {
    if (ctx.unrepresentable === "throw") {
      throw new Error("Set cannot be represented in JSON Schema");
    }
  };
  const arrayProcessor = (schema, ctx, _json, params) => {
    const json2 = _json;
    const def = schema._zod.def;
    const { minimum, maximum } = schema._zod.bag;
    if (typeof minimum === "number")
      json2.minItems = minimum;
    if (typeof maximum === "number")
      json2.maxItems = maximum;
    json2.type = "array";
    json2.items = process$2(def.element, ctx, __spreadProps(__spreadValues({}, params), { path: [...params.path, "items"] }));
  };
  const objectProcessor = (schema, ctx, _json, params) => {
    var _a3;
    const json2 = _json;
    const def = schema._zod.def;
    json2.type = "object";
    json2.properties = {};
    const shape = def.shape;
    for (const key in shape) {
      json2.properties[key] = process$2(shape[key], ctx, __spreadProps(__spreadValues({}, params), {
        path: [...params.path, "properties", key]
      }));
    }
    const allKeys = new Set(Object.keys(shape));
    const requiredKeys = new Set([...allKeys].filter((key) => {
      const v = def.shape[key]._zod;
      if (ctx.io === "input") {
        return v.optin === void 0;
      } else {
        return v.optout === void 0;
      }
    }));
    if (requiredKeys.size > 0) {
      json2.required = Array.from(requiredKeys);
    }
    if (((_a3 = def.catchall) == null ? void 0 : _a3._zod.def.type) === "never") {
      json2.additionalProperties = false;
    } else if (!def.catchall) {
      if (ctx.io === "output")
        json2.additionalProperties = false;
    } else if (def.catchall) {
      json2.additionalProperties = process$2(def.catchall, ctx, __spreadProps(__spreadValues({}, params), {
        path: [...params.path, "additionalProperties"]
      }));
    }
  };
  const unionProcessor = (schema, ctx, json2, params) => {
    const def = schema._zod.def;
    const isExclusive = def.inclusive === false;
    const options = def.options.map((x, i2) => process$2(x, ctx, __spreadProps(__spreadValues({}, params), {
      path: [...params.path, isExclusive ? "oneOf" : "anyOf", i2]
    })));
    if (isExclusive) {
      json2.oneOf = options;
    } else {
      json2.anyOf = options;
    }
  };
  const intersectionProcessor = (schema, ctx, json2, params) => {
    const def = schema._zod.def;
    const a = process$2(def.left, ctx, __spreadProps(__spreadValues({}, params), {
      path: [...params.path, "allOf", 0]
    }));
    const b = process$2(def.right, ctx, __spreadProps(__spreadValues({}, params), {
      path: [...params.path, "allOf", 1]
    }));
    const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1;
    const allOf2 = [
      ...isSimpleIntersection(a) ? a.allOf : [a],
      ...isSimpleIntersection(b) ? b.allOf : [b]
    ];
    json2.allOf = allOf2;
  };
  const tupleProcessor = (schema, ctx, _json, params) => {
    const json2 = _json;
    const def = schema._zod.def;
    json2.type = "array";
    const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items";
    const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems";
    const prefixItems2 = def.items.map((x, i2) => process$2(x, ctx, __spreadProps(__spreadValues({}, params), {
      path: [...params.path, prefixPath, i2]
    })));
    const rest = def.rest ? process$2(def.rest, ctx, __spreadProps(__spreadValues({}, params), {
      path: [...params.path, restPath, ...ctx.target === "openapi-3.0" ? [def.items.length] : []]
    })) : null;
    if (ctx.target === "draft-2020-12") {
      json2.prefixItems = prefixItems2;
      if (rest) {
        json2.items = rest;
      }
    } else if (ctx.target === "openapi-3.0") {
      json2.items = {
        anyOf: prefixItems2
      };
      if (rest) {
        json2.items.anyOf.push(rest);
      }
      json2.minItems = prefixItems2.length;
      if (!rest) {
        json2.maxItems = prefixItems2.length;
      }
    } else {
      json2.items = prefixItems2;
      if (rest) {
        json2.additionalItems = rest;
      }
    }
    const { minimum, maximum } = schema._zod.bag;
    if (typeof minimum === "number")
      json2.minItems = minimum;
    if (typeof maximum === "number")
      json2.maxItems = maximum;
  };
  const recordProcessor = (schema, ctx, _json, params) => {
    const json2 = _json;
    const def = schema._zod.def;
    json2.type = "object";
    if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") {
      json2.propertyNames = process$2(def.keyType, ctx, __spreadProps(__spreadValues({}, params), {
        path: [...params.path, "propertyNames"]
      }));
    }
    json2.additionalProperties = process$2(def.valueType, ctx, __spreadProps(__spreadValues({}, params), {
      path: [...params.path, "additionalProperties"]
    }));
  };
  const nullableProcessor = (schema, ctx, json2, params) => {
    const def = schema._zod.def;
    const inner = process$2(def.innerType, ctx, params);
    const seen = ctx.seen.get(schema);
    if (ctx.target === "openapi-3.0") {
      seen.ref = def.innerType;
      json2.nullable = true;
    } else {
      json2.anyOf = [inner, { type: "null" }];
    }
  };
  const nonoptionalProcessor = (schema, ctx, _json, params) => {
    const def = schema._zod.def;
    process$2(def.innerType, ctx, params);
    const seen = ctx.seen.get(schema);
    seen.ref = def.innerType;
  };
  const defaultProcessor = (schema, ctx, json2, params) => {
    const def = schema._zod.def;
    process$2(def.innerType, ctx, params);
    const seen = ctx.seen.get(schema);
    seen.ref = def.innerType;
    json2.default = JSON.parse(JSON.stringify(def.defaultValue));
  };
  const prefaultProcessor = (schema, ctx, json2, params) => {
    const def = schema._zod.def;
    process$2(def.innerType, ctx, params);
    const seen = ctx.seen.get(schema);
    seen.ref = def.innerType;
    if (ctx.io === "input")
      json2._prefault = JSON.parse(JSON.stringify(def.defaultValue));
  };
  const catchProcessor = (schema, ctx, json2, params) => {
    const def = schema._zod.def;
    process$2(def.innerType, ctx, params);
    const seen = ctx.seen.get(schema);
    seen.ref = def.innerType;
    let catchValue;
    try {
      catchValue = def.catchValue(void 0);
    } catch (e) {
      throw new Error("Dynamic catch values are not supported in JSON Schema");
    }
    json2.default = catchValue;
  };
  const pipeProcessor = (schema, ctx, _json, params) => {
    const def = schema._zod.def;
    const innerType = ctx.io === "input" ? def.in._zod.def.type === "transform" ? def.out : def.in : def.out;
    process$2(innerType, ctx, params);
    const seen = ctx.seen.get(schema);
    seen.ref = innerType;
  };
  const readonlyProcessor = (schema, ctx, json2, params) => {
    const def = schema._zod.def;
    process$2(def.innerType, ctx, params);
    const seen = ctx.seen.get(schema);
    seen.ref = def.innerType;
    json2.readOnly = true;
  };
  const promiseProcessor = (schema, ctx, _json, params) => {
    const def = schema._zod.def;
    process$2(def.innerType, ctx, params);
    const seen = ctx.seen.get(schema);
    seen.ref = def.innerType;
  };
  const optionalProcessor = (schema, ctx, _json, params) => {
    const def = schema._zod.def;
    process$2(def.innerType, ctx, params);
    const seen = ctx.seen.get(schema);
    seen.ref = def.innerType;
  };
  const lazyProcessor = (schema, ctx, _json, params) => {
    const innerType = schema._zod.innerType;
    process$2(innerType, ctx, params);
    const seen = ctx.seen.get(schema);
    seen.ref = innerType;
  };
  const allProcessors = {
    string: stringProcessor,
    number: numberProcessor,
    boolean: booleanProcessor,
    bigint: bigintProcessor,
    symbol: symbolProcessor,
    null: nullProcessor,
    undefined: undefinedProcessor,
    void: voidProcessor,
    never: neverProcessor,
    any: anyProcessor,
    unknown: unknownProcessor,
    date: dateProcessor,
    enum: enumProcessor,
    literal: literalProcessor,
    nan: nanProcessor,
    template_literal: templateLiteralProcessor,
    file: fileProcessor,
    success: successProcessor,
    custom: customProcessor,
    function: functionProcessor,
    transform: transformProcessor,
    map: mapProcessor,
    set: setProcessor,
    array: arrayProcessor,
    object: objectProcessor,
    union: unionProcessor,
    intersection: intersectionProcessor,
    tuple: tupleProcessor,
    record: recordProcessor,
    nullable: nullableProcessor,
    nonoptional: nonoptionalProcessor,
    default: defaultProcessor,
    prefault: prefaultProcessor,
    catch: catchProcessor,
    pipe: pipeProcessor,
    readonly: readonlyProcessor,
    promise: promiseProcessor,
    optional: optionalProcessor,
    lazy: lazyProcessor
  };
  function toJSONSchema(input, params) {
    if ("_idmap" in input) {
      const registry2 = input;
      const ctx2 = initializeContext(__spreadProps(__spreadValues({}, params), { processors: allProcessors }));
      const defs = {};
      for (const entry of registry2._idmap.entries()) {
        const [_, schema] = entry;
        process$2(schema, ctx2);
      }
      const schemas = {};
      const external = {
        registry: registry2,
        uri: params == null ? void 0 : params.uri,
        defs
      };
      ctx2.external = external;
      for (const entry of registry2._idmap.entries()) {
        const [key, schema] = entry;
        extractDefs(ctx2, schema);
        schemas[key] = finalize(ctx2, schema);
      }
      if (Object.keys(defs).length > 0) {
        const defsSegment = ctx2.target === "draft-2020-12" ? "$defs" : "definitions";
        schemas.__shared = {
          [defsSegment]: defs
        };
      }
      return { schemas };
    }
    const ctx = initializeContext(__spreadProps(__spreadValues({}, params), { processors: allProcessors }));
    process$2(input, ctx);
    extractDefs(ctx, input);
    return finalize(ctx, input);
  }
  class JSONSchemaGenerator {
    /** @deprecated Access via ctx instead */
    get metadataRegistry() {
      return this.ctx.metadataRegistry;
    }
    /** @deprecated Access via ctx instead */
    get target() {
      return this.ctx.target;
    }
    /** @deprecated Access via ctx instead */
    get unrepresentable() {
      return this.ctx.unrepresentable;
    }
    /** @deprecated Access via ctx instead */
    get override() {
      return this.ctx.override;
    }
    /** @deprecated Access via ctx instead */
    get io() {
      return this.ctx.io;
    }
    /** @deprecated Access via ctx instead */
    get counter() {
      return this.ctx.counter;
    }
    set counter(value) {
      this.ctx.counter = value;
    }
    /** @deprecated Access via ctx instead */
    get seen() {
      return this.ctx.seen;
    }
    constructor(params) {
      var _a3;
      let normalizedTarget = (_a3 = params == null ? void 0 : params.target) != null ? _a3 : "draft-2020-12";
      if (normalizedTarget === "draft-4")
        normalizedTarget = "draft-04";
      if (normalizedTarget === "draft-7")
        normalizedTarget = "draft-07";
      this.ctx = initializeContext(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
        processors: allProcessors,
        target: normalizedTarget
      }, (params == null ? void 0 : params.metadata) && { metadata: params.metadata }), (params == null ? void 0 : params.unrepresentable) && { unrepresentable: params.unrepresentable }), (params == null ? void 0 : params.override) && { override: params.override }), (params == null ? void 0 : params.io) && { io: params.io }));
    }
    /**
     * Process a schema to prepare it for JSON Schema generation.
     * This must be called before emit().
     */
    process(schema, _params = { path: [], schemaPath: [] }) {
      return process$2(schema, this.ctx, _params);
    }
    /**
     * Emit the final JSON Schema after processing.
     * Must call process() first.
     */
    emit(schema, _params) {
      if (_params) {
        if (_params.cycles)
          this.ctx.cycles = _params.cycles;
        if (_params.reused)
          this.ctx.reused = _params.reused;
        if (_params.external)
          this.ctx.external = _params.external;
      }
      extractDefs(this.ctx, schema);
      const result2 = finalize(this.ctx, schema);
      const _a3 = result2, { "~standard": _ } = _a3, plainResult = __objRest(_a3, ["~standard"]);
      return plainResult;
    }
  }
  const jsonSchema = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
    __proto__: null
  }, Symbol.toStringTag, { value: "Module" }));
  const index$4 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
    __proto__: null,
    $ZodAny,
    $ZodArray,
    $ZodAsyncError,
    $ZodBase64,
    $ZodBase64URL,
    $ZodBigInt,
    $ZodBigIntFormat,
    $ZodBoolean,
    $ZodCIDRv4,
    $ZodCIDRv6,
    $ZodCUID,
    $ZodCUID2,
    $ZodCatch,
    $ZodCheck,
    $ZodCheckBigIntFormat,
    $ZodCheckEndsWith,
    $ZodCheckGreaterThan,
    $ZodCheckIncludes,
    $ZodCheckLengthEquals,
    $ZodCheckLessThan,
    $ZodCheckLowerCase,
    $ZodCheckMaxLength,
    $ZodCheckMaxSize,
    $ZodCheckMimeType,
    $ZodCheckMinLength,
    $ZodCheckMinSize,
    $ZodCheckMultipleOf,
    $ZodCheckNumberFormat,
    $ZodCheckOverwrite,
    $ZodCheckProperty,
    $ZodCheckRegex,
    $ZodCheckSizeEquals,
    $ZodCheckStartsWith,
    $ZodCheckStringFormat,
    $ZodCheckUpperCase,
    $ZodCodec,
    $ZodCustom,
    $ZodCustomStringFormat,
    $ZodDate,
    $ZodDefault,
    $ZodDiscriminatedUnion,
    $ZodE164,
    $ZodEmail,
    $ZodEmoji,
    $ZodEncodeError,
    $ZodEnum,
    $ZodError,
    $ZodFile,
    $ZodFunction,
    $ZodGUID,
    $ZodIPv4,
    $ZodIPv6,
    $ZodISODate,
    $ZodISODateTime,
    $ZodISODuration,
    $ZodISOTime,
    $ZodIntersection,
    $ZodJWT,
    $ZodKSUID,
    $ZodLazy,
    $ZodLiteral,
    $ZodMAC,
    $ZodMap,
    $ZodNaN,
    $ZodNanoID,
    $ZodNever,
    $ZodNonOptional,
    $ZodNull,
    $ZodNullable,
    $ZodNumber,
    $ZodNumberFormat,
    $ZodObject,
    $ZodObjectJIT,
    $ZodOptional,
    $ZodPipe,
    $ZodPrefault,
    $ZodPromise,
    $ZodReadonly,
    $ZodRealError,
    $ZodRecord,
    $ZodRegistry,
    $ZodSet,
    $ZodString,
    $ZodStringFormat,
    $ZodSuccess,
    $ZodSymbol,
    $ZodTemplateLiteral,
    $ZodTransform,
    $ZodTuple,
    $ZodType,
    $ZodULID,
    $ZodURL,
    $ZodUUID,
    $ZodUndefined,
    $ZodUnion,
    $ZodUnknown,
    $ZodVoid,
    $ZodXID,
    $ZodXor,
    $brand,
    $constructor,
    $input,
    $output,
    Doc,
    JSONSchema: jsonSchema,
    JSONSchemaGenerator,
    NEVER,
    TimePrecision,
    _any,
    _array,
    _base64,
    _base64url,
    _bigint,
    _boolean,
    _catch: _catch$1,
    _check,
    _cidrv4,
    _cidrv6,
    _coercedBigint,
    _coercedBoolean,
    _coercedDate,
    _coercedNumber,
    _coercedString,
    _cuid,
    _cuid2,
    _custom,
    _date,
    _decode,
    _decodeAsync,
    _default: _default$1,
    _discriminatedUnion,
    _e164,
    _email,
    _emoji,
    _encode,
    _encodeAsync,
    _endsWith,
    _enum: _enum$2,
    _file,
    _float32,
    _float64,
    _gt,
    _gte,
    _guid,
    _includes,
    _int,
    _int32,
    _int64,
    _intersection,
    _ipv4,
    _ipv6,
    _isoDate,
    _isoDateTime,
    _isoDuration,
    _isoTime,
    _jwt,
    _ksuid,
    _lazy,
    _length,
    _literal,
    _lowercase,
    _lt,
    _lte,
    _mac,
    _map,
    _max: _lte,
    _maxLength,
    _maxSize,
    _mime,
    _min: _gte,
    _minLength,
    _minSize,
    _multipleOf,
    _nan,
    _nanoid,
    _nativeEnum,
    _negative,
    _never,
    _nonnegative,
    _nonoptional,
    _nonpositive,
    _normalize,
    _null: _null$1,
    _nullable,
    _number,
    _optional,
    _overwrite,
    _parse,
    _parseAsync,
    _pipe,
    _positive,
    _promise,
    _property,
    _readonly,
    _record,
    _refine,
    _regex,
    _safeDecode,
    _safeDecodeAsync,
    _safeEncode,
    _safeEncodeAsync,
    _safeParse,
    _safeParseAsync,
    _set,
    _size,
    _slugify,
    _startsWith,
    _string,
    _stringFormat,
    _stringbool,
    _success,
    _superRefine,
    _symbol,
    _templateLiteral,
    _toLowerCase,
    _toUpperCase,
    _transform,
    _trim,
    _tuple,
    _uint32,
    _uint64,
    _ulid,
    _undefined: _undefined$1,
    _union,
    _unknown,
    _uppercase,
    _url,
    _uuid,
    _uuidv4,
    _uuidv6,
    _uuidv7,
    _void: _void$1,
    _xid,
    _xor,
    clone,
    config,
    createStandardJSONSchemaMethod,
    createToJSONSchemaMethod,
    decode: decode$1,
    decodeAsync: decodeAsync$1,
    describe: describe$1,
    encode: encode$1,
    encodeAsync: encodeAsync$1,
    extractDefs,
    finalize,
    flattenError,
    formatError,
    globalConfig,
    globalRegistry,
    initializeContext,
    isValidBase64,
    isValidBase64URL,
    isValidJWT,
    locales: index$5,
    meta: meta$1,
    parse: parse$1,
    parseAsync: parseAsync$1,
    prettifyError,
    process: process$2,
    regexes,
    registry,
    safeDecode: safeDecode$1,
    safeDecodeAsync: safeDecodeAsync$1,
    safeEncode: safeEncode$1,
    safeEncodeAsync: safeEncodeAsync$1,
    safeParse: safeParse$2,
    safeParseAsync: safeParseAsync$1,
    toDotPath,
    toJSONSchema,
    treeifyError,
    util: util$1,
    version
  }, Symbol.toStringTag, { value: "Module" }));
  function isZ4Schema(s) {
    const schema = s;
    return !!schema._zod;
  }
  function safeParse$1(schema, data) {
    if (isZ4Schema(schema)) {
      const result3 = safeParse$2(schema, data);
      return result3;
    }
    const v3Schema = schema;
    const result2 = v3Schema.safeParse(data);
    return result2;
  }
  function getObjectShape(schema) {
    var _a3, _b2;
    if (!schema)
      return void 0;
    let rawShape;
    if (isZ4Schema(schema)) {
      const v4Schema = schema;
      rawShape = (_b2 = (_a3 = v4Schema._zod) == null ? void 0 : _a3.def) == null ? void 0 : _b2.shape;
    } else {
      const v3Schema = schema;
      rawShape = v3Schema.shape;
    }
    if (!rawShape)
      return void 0;
    if (typeof rawShape === "function") {
      try {
        return rawShape();
      } catch (e) {
        return void 0;
      }
    }
    return rawShape;
  }
  function getLiteralValue(schema) {
    var _a3;
    if (isZ4Schema(schema)) {
      const v4Schema = schema;
      const def2 = (_a3 = v4Schema._zod) == null ? void 0 : _a3.def;
      if (def2) {
        if (def2.value !== void 0)
          return def2.value;
        if (Array.isArray(def2.values) && def2.values.length > 0) {
          return def2.values[0];
        }
      }
    }
    const v3Schema = schema;
    const def = v3Schema._def;
    if (def) {
      if (def.value !== void 0)
        return def.value;
      if (Array.isArray(def.values) && def.values.length > 0) {
        return def.values[0];
      }
    }
    const directValue = schema.value;
    if (directValue !== void 0)
      return directValue;
    return void 0;
  }
  const _checks = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
    __proto__: null,
    endsWith: _endsWith,
    gt: _gt,
    gte: _gte,
    includes: _includes,
    length: _length,
    lowercase: _lowercase,
    lt: _lt,
    lte: _lte,
    maxLength: _maxLength,
    maxSize: _maxSize,
    mime: _mime,
    minLength: _minLength,
    minSize: _minSize,
    multipleOf: _multipleOf,
    negative: _negative,
    nonnegative: _nonnegative,
    nonpositive: _nonpositive,
    normalize: _normalize,
    overwrite: _overwrite,
    positive: _positive,
    property: _property,
    regex: _regex,
    size: _size,
    slugify: _slugify,
    startsWith: _startsWith,
    toLowerCase: _toLowerCase,
    toUpperCase: _toUpperCase,
    trim: _trim,
    uppercase: _uppercase
  }, Symbol.toStringTag, { value: "Module" }));
  const ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => {
    $ZodISODateTime.init(inst, def);
    ZodStringFormat.init(inst, def);
  });
  function datetime(params) {
    return _isoDateTime(ZodISODateTime, params);
  }
  const ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => {
    $ZodISODate.init(inst, def);
    ZodStringFormat.init(inst, def);
  });
  function date$2(params) {
    return _isoDate(ZodISODate, params);
  }
  const ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => {
    $ZodISOTime.init(inst, def);
    ZodStringFormat.init(inst, def);
  });
  function time(params) {
    return _isoTime(ZodISOTime, params);
  }
  const ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => {
    $ZodISODuration.init(inst, def);
    ZodStringFormat.init(inst, def);
  });
  function duration(params) {
    return _isoDuration(ZodISODuration, params);
  }
  const _iso = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
    __proto__: null,
    ZodISODate,
    ZodISODateTime,
    ZodISODuration,
    ZodISOTime,
    date: date$2,
    datetime,
    duration,
    time
  }, Symbol.toStringTag, { value: "Module" }));
  const initializer = (inst, issues) => {
    $ZodError.init(inst, issues);
    inst.name = "ZodError";
    Object.defineProperties(inst, {
      format: {
        value: (mapper) => formatError(inst, mapper)
        // enumerable: false,
      },
      flatten: {
        value: (mapper) => flattenError(inst, mapper)
        // enumerable: false,
      },
      addIssue: {
        value: (issue2) => {
          inst.issues.push(issue2);
          inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
        }
        // enumerable: false,
      },
      addIssues: {
        value: (issues2) => {
          inst.issues.push(...issues2);
          inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
        }
        // enumerable: false,
      },
      isEmpty: {
        get() {
          return inst.issues.length === 0;
        }
        // enumerable: false,
      }
    });
  };
  const ZodError = $constructor("ZodError", initializer);
  const ZodRealError = $constructor("ZodError", initializer, {
    Parent: Error
  });
  const parse = /* @__PURE__ */ _parse(ZodRealError);
  const parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError);
  const safeParse = /* @__PURE__ */ _safeParse(ZodRealError);
  const safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError);
  const encode = /* @__PURE__ */ _encode(ZodRealError);
  const decode = /* @__PURE__ */ _decode(ZodRealError);
  const encodeAsync = /* @__PURE__ */ _encodeAsync(ZodRealError);
  const decodeAsync = /* @__PURE__ */ _decodeAsync(ZodRealError);
  const safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError);
  const safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError);
  const safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError);
  const safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError);
  const ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {
    $ZodType.init(inst, def);
    Object.assign(inst["~standard"], {
      jsonSchema: {
        input: createStandardJSONSchemaMethod(inst, "input"),
        output: createStandardJSONSchemaMethod(inst, "output")
      }
    });
    inst.toJSONSchema = createToJSONSchemaMethod(inst, {});
    inst.def = def;
    inst.type = def.type;
    Object.defineProperty(inst, "_def", { value: def });
    inst.check = (...checks) => {
      var _a3;
      return inst.clone(mergeDefs(def, {
        checks: [
          ...(_a3 = def.checks) != null ? _a3 : [],
          ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch)
        ]
      }));
    };
    inst.clone = (def2, params) => clone(inst, def2, params);
    inst.brand = () => inst;
    inst.register = ((reg, meta2) => {
      reg.add(inst, meta2);
      return inst;
    });
    inst.parse = (data, params) => parse(inst, data, params, { callee: inst.parse });
    inst.safeParse = (data, params) => safeParse(inst, data, params);
    inst.parseAsync = (data, params) => __async(null, null, function* () {
      return parseAsync(inst, data, params, { callee: inst.parseAsync });
    });
    inst.safeParseAsync = (data, params) => __async(null, null, function* () {
      return safeParseAsync(inst, data, params);
    });
    inst.spa = inst.safeParseAsync;
    inst.encode = (data, params) => encode(inst, data, params);
    inst.decode = (data, params) => decode(inst, data, params);
    inst.encodeAsync = (data, params) => __async(null, null, function* () {
      return encodeAsync(inst, data, params);
    });
    inst.decodeAsync = (data, params) => __async(null, null, function* () {
      return decodeAsync(inst, data, params);
    });
    inst.safeEncode = (data, params) => safeEncode(inst, data, params);
    inst.safeDecode = (data, params) => safeDecode(inst, data, params);
    inst.safeEncodeAsync = (data, params) => __async(null, null, function* () {
      return safeEncodeAsync(inst, data, params);
    });
    inst.safeDecodeAsync = (data, params) => __async(null, null, function* () {
      return safeDecodeAsync(inst, data, params);
    });
    inst.refine = (check2, params) => inst.check(refine(check2, params));
    inst.superRefine = (refinement) => inst.check(superRefine(refinement));
    inst.overwrite = (fn) => inst.check(_overwrite(fn));
    inst.optional = () => optional(inst);
    inst.nullable = () => nullable(inst);
    inst.nullish = () => optional(nullable(inst));
    inst.nonoptional = (params) => nonoptional(inst, params);
    inst.array = () => array(inst);
    inst.or = (arg) => union([inst, arg]);
    inst.and = (arg) => intersection(inst, arg);
    inst.transform = (tx) => pipe(inst, transform(tx));
    inst.default = (def2) => _default(inst, def2);
    inst.prefault = (def2) => prefault(inst, def2);
    inst.catch = (params) => _catch(inst, params);
    inst.pipe = (target) => pipe(inst, target);
    inst.readonly = () => readonly(inst);
    inst.describe = (description2) => {
      const cl = inst.clone();
      globalRegistry.add(cl, { description: description2 });
      return cl;
    };
    Object.defineProperty(inst, "description", {
      get() {
        var _a3;
        return (_a3 = globalRegistry.get(inst)) == null ? void 0 : _a3.description;
      },
      configurable: true
    });
    inst.meta = (...args) => {
      if (args.length === 0) {
        return globalRegistry.get(inst);
      }
      const cl = inst.clone();
      globalRegistry.add(cl, args[0]);
      return cl;
    };
    inst.isOptional = () => inst.safeParse(void 0).success;
    inst.isNullable = () => inst.safeParse(null).success;
    return inst;
  });
  const _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => {
    var _a3, _b2, _c2;
    $ZodString.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => stringProcessor(inst, ctx, json2);
    const bag = inst._zod.bag;
    inst.format = (_a3 = bag.format) != null ? _a3 : null;
    inst.minLength = (_b2 = bag.minimum) != null ? _b2 : null;
    inst.maxLength = (_c2 = bag.maximum) != null ? _c2 : null;
    inst.regex = (...args) => inst.check(_regex(...args));
    inst.includes = (...args) => inst.check(_includes(...args));
    inst.startsWith = (...args) => inst.check(_startsWith(...args));
    inst.endsWith = (...args) => inst.check(_endsWith(...args));
    inst.min = (...args) => inst.check(_minLength(...args));
    inst.max = (...args) => inst.check(_maxLength(...args));
    inst.length = (...args) => inst.check(_length(...args));
    inst.nonempty = (...args) => inst.check(_minLength(1, ...args));
    inst.lowercase = (params) => inst.check(_lowercase(params));
    inst.uppercase = (params) => inst.check(_uppercase(params));
    inst.trim = () => inst.check(_trim());
    inst.normalize = (...args) => inst.check(_normalize(...args));
    inst.toLowerCase = () => inst.check(_toLowerCase());
    inst.toUpperCase = () => inst.check(_toUpperCase());
    inst.slugify = () => inst.check(_slugify());
  });
  const ZodString = /* @__PURE__ */ $constructor("ZodString", (inst, def) => {
    $ZodString.init(inst, def);
    _ZodString.init(inst, def);
    inst.email = (params) => inst.check(_email(ZodEmail, params));
    inst.url = (params) => inst.check(_url(ZodURL, params));
    inst.jwt = (params) => inst.check(_jwt(ZodJWT, params));
    inst.emoji = (params) => inst.check(_emoji(ZodEmoji, params));
    inst.guid = (params) => inst.check(_guid(ZodGUID, params));
    inst.uuid = (params) => inst.check(_uuid(ZodUUID, params));
    inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params));
    inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params));
    inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params));
    inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params));
    inst.guid = (params) => inst.check(_guid(ZodGUID, params));
    inst.cuid = (params) => inst.check(_cuid(ZodCUID, params));
    inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params));
    inst.ulid = (params) => inst.check(_ulid(ZodULID, params));
    inst.base64 = (params) => inst.check(_base64(ZodBase64, params));
    inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params));
    inst.xid = (params) => inst.check(_xid(ZodXID, params));
    inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params));
    inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params));
    inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params));
    inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params));
    inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params));
    inst.e164 = (params) => inst.check(_e164(ZodE164, params));
    inst.datetime = (params) => inst.check(datetime(params));
    inst.date = (params) => inst.check(date$2(params));
    inst.time = (params) => inst.check(time(params));
    inst.duration = (params) => inst.check(duration(params));
  });
  function string$1(params) {
    return _string(ZodString, params);
  }
  const ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => {
    $ZodStringFormat.init(inst, def);
    _ZodString.init(inst, def);
  });
  const ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => {
    $ZodEmail.init(inst, def);
    ZodStringFormat.init(inst, def);
  });
  function email(params) {
    return _email(ZodEmail, params);
  }
  const ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => {
    $ZodGUID.init(inst, def);
    ZodStringFormat.init(inst, def);
  });
  function guid(params) {
    return _guid(ZodGUID, params);
  }
  const ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => {
    $ZodUUID.init(inst, def);
    ZodStringFormat.init(inst, def);
  });
  function uuid(params) {
    return _uuid(ZodUUID, params);
  }
  function uuidv4(params) {
    return _uuidv4(ZodUUID, params);
  }
  function uuidv6(params) {
    return _uuidv6(ZodUUID, params);
  }
  function uuidv7(params) {
    return _uuidv7(ZodUUID, params);
  }
  const ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => {
    $ZodURL.init(inst, def);
    ZodStringFormat.init(inst, def);
  });
  function url(params) {
    return _url(ZodURL, params);
  }
  function httpUrl(params) {
    return _url(ZodURL, __spreadValues({
      protocol: /^https?$/,
      hostname: domain
    }, normalizeParams(params)));
  }
  const ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => {
    $ZodEmoji.init(inst, def);
    ZodStringFormat.init(inst, def);
  });
  function emoji(params) {
    return _emoji(ZodEmoji, params);
  }
  const ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => {
    $ZodNanoID.init(inst, def);
    ZodStringFormat.init(inst, def);
  });
  function nanoid$1(params) {
    return _nanoid(ZodNanoID, params);
  }
  const ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => {
    $ZodCUID.init(inst, def);
    ZodStringFormat.init(inst, def);
  });
  function cuid(params) {
    return _cuid(ZodCUID, params);
  }
  const ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def) => {
    $ZodCUID2.init(inst, def);
    ZodStringFormat.init(inst, def);
  });
  function cuid2(params) {
    return _cuid2(ZodCUID2, params);
  }
  const ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def) => {
    $ZodULID.init(inst, def);
    ZodStringFormat.init(inst, def);
  });
  function ulid(params) {
    return _ulid(ZodULID, params);
  }
  const ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def) => {
    $ZodXID.init(inst, def);
    ZodStringFormat.init(inst, def);
  });
  function xid(params) {
    return _xid(ZodXID, params);
  }
  const ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def) => {
    $ZodKSUID.init(inst, def);
    ZodStringFormat.init(inst, def);
  });
  function ksuid(params) {
    return _ksuid(ZodKSUID, params);
  }
  const ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def) => {
    $ZodIPv4.init(inst, def);
    ZodStringFormat.init(inst, def);
  });
  function ipv4(params) {
    return _ipv4(ZodIPv4, params);
  }
  const ZodMAC = /* @__PURE__ */ $constructor("ZodMAC", (inst, def) => {
    $ZodMAC.init(inst, def);
    ZodStringFormat.init(inst, def);
  });
  function mac(params) {
    return _mac(ZodMAC, params);
  }
  const ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def) => {
    $ZodIPv6.init(inst, def);
    ZodStringFormat.init(inst, def);
  });
  function ipv6(params) {
    return _ipv6(ZodIPv6, params);
  }
  const ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def) => {
    $ZodCIDRv4.init(inst, def);
    ZodStringFormat.init(inst, def);
  });
  function cidrv4(params) {
    return _cidrv4(ZodCIDRv4, params);
  }
  const ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def) => {
    $ZodCIDRv6.init(inst, def);
    ZodStringFormat.init(inst, def);
  });
  function cidrv6(params) {
    return _cidrv6(ZodCIDRv6, params);
  }
  const ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => {
    $ZodBase64.init(inst, def);
    ZodStringFormat.init(inst, def);
  });
  function base64(params) {
    return _base64(ZodBase64, params);
  }
  const ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => {
    $ZodBase64URL.init(inst, def);
    ZodStringFormat.init(inst, def);
  });
  function base64url(params) {
    return _base64url(ZodBase64URL, params);
  }
  const ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => {
    $ZodE164.init(inst, def);
    ZodStringFormat.init(inst, def);
  });
  function e164(params) {
    return _e164(ZodE164, params);
  }
  const ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => {
    $ZodJWT.init(inst, def);
    ZodStringFormat.init(inst, def);
  });
  function jwt(params) {
    return _jwt(ZodJWT, params);
  }
  const ZodCustomStringFormat = /* @__PURE__ */ $constructor("ZodCustomStringFormat", (inst, def) => {
    $ZodCustomStringFormat.init(inst, def);
    ZodStringFormat.init(inst, def);
  });
  function stringFormat(format2, fnOrRegex, _params = {}) {
    return _stringFormat(ZodCustomStringFormat, format2, fnOrRegex, _params);
  }
  function hostname(_params) {
    return _stringFormat(ZodCustomStringFormat, "hostname", hostname$1, _params);
  }
  function hex(_params) {
    return _stringFormat(ZodCustomStringFormat, "hex", hex$1, _params);
  }
  function hash(alg, params) {
    var _a3;
    const enc = (_a3 = params == null ? void 0 : params.enc) != null ? _a3 : "hex";
    const format2 = `${alg}_${enc}`;
    const regex = regexes[format2];
    if (!regex)
      throw new Error(`Unrecognized hash format: ${format2}`);
    return _stringFormat(ZodCustomStringFormat, format2, regex, params);
  }
  const ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => {
    var _a3, _b2, _c2, _d2, _e, _f, _g, _h, _i;
    $ZodNumber.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => numberProcessor(inst, ctx, json2);
    inst.gt = (value, params) => inst.check(_gt(value, params));
    inst.gte = (value, params) => inst.check(_gte(value, params));
    inst.min = (value, params) => inst.check(_gte(value, params));
    inst.lt = (value, params) => inst.check(_lt(value, params));
    inst.lte = (value, params) => inst.check(_lte(value, params));
    inst.max = (value, params) => inst.check(_lte(value, params));
    inst.int = (params) => inst.check(int(params));
    inst.safe = (params) => inst.check(int(params));
    inst.positive = (params) => inst.check(_gt(0, params));
    inst.nonnegative = (params) => inst.check(_gte(0, params));
    inst.negative = (params) => inst.check(_lt(0, params));
    inst.nonpositive = (params) => inst.check(_lte(0, params));
    inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params));
    inst.step = (value, params) => inst.check(_multipleOf(value, params));
    inst.finite = () => inst;
    const bag = inst._zod.bag;
    inst.minValue = (_c2 = Math.max((_a3 = bag.minimum) != null ? _a3 : Number.NEGATIVE_INFINITY, (_b2 = bag.exclusiveMinimum) != null ? _b2 : Number.NEGATIVE_INFINITY)) != null ? _c2 : null;
    inst.maxValue = (_f = Math.min((_d2 = bag.maximum) != null ? _d2 : Number.POSITIVE_INFINITY, (_e = bag.exclusiveMaximum) != null ? _e : Number.POSITIVE_INFINITY)) != null ? _f : null;
    inst.isInt = ((_g = bag.format) != null ? _g : "").includes("int") || Number.isSafeInteger((_h = bag.multipleOf) != null ? _h : 0.5);
    inst.isFinite = true;
    inst.format = (_i = bag.format) != null ? _i : null;
  });
  function number$1(params) {
    return _number(ZodNumber, params);
  }
  const ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => {
    $ZodNumberFormat.init(inst, def);
    ZodNumber.init(inst, def);
  });
  function int(params) {
    return _int(ZodNumberFormat, params);
  }
  function float32(params) {
    return _float32(ZodNumberFormat, params);
  }
  function float64(params) {
    return _float64(ZodNumberFormat, params);
  }
  function int32(params) {
    return _int32(ZodNumberFormat, params);
  }
  function uint32(params) {
    return _uint32(ZodNumberFormat, params);
  }
  const ZodBoolean = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => {
    $ZodBoolean.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => booleanProcessor(inst, ctx, json2);
  });
  function boolean$1(params) {
    return _boolean(ZodBoolean, params);
  }
  const ZodBigInt = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def) => {
    var _a3, _b2, _c2;
    $ZodBigInt.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => bigintProcessor(inst, ctx);
    inst.gte = (value, params) => inst.check(_gte(value, params));
    inst.min = (value, params) => inst.check(_gte(value, params));
    inst.gt = (value, params) => inst.check(_gt(value, params));
    inst.gte = (value, params) => inst.check(_gte(value, params));
    inst.min = (value, params) => inst.check(_gte(value, params));
    inst.lt = (value, params) => inst.check(_lt(value, params));
    inst.lte = (value, params) => inst.check(_lte(value, params));
    inst.max = (value, params) => inst.check(_lte(value, params));
    inst.positive = (params) => inst.check(_gt(BigInt(0), params));
    inst.negative = (params) => inst.check(_lt(BigInt(0), params));
    inst.nonpositive = (params) => inst.check(_lte(BigInt(0), params));
    inst.nonnegative = (params) => inst.check(_gte(BigInt(0), params));
    inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params));
    const bag = inst._zod.bag;
    inst.minValue = (_a3 = bag.minimum) != null ? _a3 : null;
    inst.maxValue = (_b2 = bag.maximum) != null ? _b2 : null;
    inst.format = (_c2 = bag.format) != null ? _c2 : null;
  });
  function bigint$1(params) {
    return _bigint(ZodBigInt, params);
  }
  const ZodBigIntFormat = /* @__PURE__ */ $constructor("ZodBigIntFormat", (inst, def) => {
    $ZodBigIntFormat.init(inst, def);
    ZodBigInt.init(inst, def);
  });
  function int64(params) {
    return _int64(ZodBigIntFormat, params);
  }
  function uint64(params) {
    return _uint64(ZodBigIntFormat, params);
  }
  const ZodSymbol = /* @__PURE__ */ $constructor("ZodSymbol", (inst, def) => {
    $ZodSymbol.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => symbolProcessor(inst, ctx);
  });
  function symbol(params) {
    return _symbol(ZodSymbol, params);
  }
  const ZodUndefined = /* @__PURE__ */ $constructor("ZodUndefined", (inst, def) => {
    $ZodUndefined.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => undefinedProcessor(inst, ctx);
  });
  function _undefined(params) {
    return _undefined$1(ZodUndefined, params);
  }
  const ZodNull = /* @__PURE__ */ $constructor("ZodNull", (inst, def) => {
    $ZodNull.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => nullProcessor(inst, ctx, json2);
  });
  function _null(params) {
    return _null$1(ZodNull, params);
  }
  const ZodAny = /* @__PURE__ */ $constructor("ZodAny", (inst, def) => {
    $ZodAny.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => anyProcessor();
  });
  function any() {
    return _any(ZodAny);
  }
  const ZodUnknown = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => {
    $ZodUnknown.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => unknownProcessor();
  });
  function unknown() {
    return _unknown(ZodUnknown);
  }
  const ZodNever = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => {
    $ZodNever.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => neverProcessor(inst, ctx, json2);
  });
  function never(params) {
    return _never(ZodNever, params);
  }
  const ZodVoid = /* @__PURE__ */ $constructor("ZodVoid", (inst, def) => {
    $ZodVoid.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => voidProcessor(inst, ctx);
  });
  function _void(params) {
    return _void$1(ZodVoid, params);
  }
  const ZodDate = /* @__PURE__ */ $constructor("ZodDate", (inst, def) => {
    $ZodDate.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => dateProcessor(inst, ctx);
    inst.min = (value, params) => inst.check(_gte(value, params));
    inst.max = (value, params) => inst.check(_lte(value, params));
    const c = inst._zod.bag;
    inst.minDate = c.minimum ? new Date(c.minimum) : null;
    inst.maxDate = c.maximum ? new Date(c.maximum) : null;
  });
  function date$1(params) {
    return _date(ZodDate, params);
  }
  const ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => {
    $ZodArray.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => arrayProcessor(inst, ctx, json2, params);
    inst.element = def.element;
    inst.min = (minLength, params) => inst.check(_minLength(minLength, params));
    inst.nonempty = (params) => inst.check(_minLength(1, params));
    inst.max = (maxLength, params) => inst.check(_maxLength(maxLength, params));
    inst.length = (len2, params) => inst.check(_length(len2, params));
    inst.unwrap = () => inst.element;
  });
  function array(element, params) {
    return _array(ZodArray, element, params);
  }
  function keyof(schema) {
    const shape = schema._zod.def.shape;
    return _enum$1(Object.keys(shape));
  }
  const ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => {
    $ZodObjectJIT.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => objectProcessor(inst, ctx, json2, params);
    defineLazy(inst, "shape", () => {
      return def.shape;
    });
    inst.keyof = () => _enum$1(Object.keys(inst._zod.def.shape));
    inst.catchall = (catchall) => inst.clone(__spreadProps(__spreadValues({}, inst._zod.def), { catchall }));
    inst.passthrough = () => inst.clone(__spreadProps(__spreadValues({}, inst._zod.def), { catchall: unknown() }));
    inst.loose = () => inst.clone(__spreadProps(__spreadValues({}, inst._zod.def), { catchall: unknown() }));
    inst.strict = () => inst.clone(__spreadProps(__spreadValues({}, inst._zod.def), { catchall: never() }));
    inst.strip = () => inst.clone(__spreadProps(__spreadValues({}, inst._zod.def), { catchall: void 0 }));
    inst.extend = (incoming) => {
      return extend(inst, incoming);
    };
    inst.safeExtend = (incoming) => {
      return safeExtend(inst, incoming);
    };
    inst.merge = (other) => merge(inst, other);
    inst.pick = (mask) => pick(inst, mask);
    inst.omit = (mask) => omit(inst, mask);
    inst.partial = (...args) => partial(ZodOptional, inst, args[0]);
    inst.required = (...args) => required$2(ZodNonOptional, inst, args[0]);
  });
  function object(shape, params) {
    const def = __spreadValues({
      type: "object",
      shape: shape != null ? shape : {}
    }, normalizeParams(params));
    return new ZodObject(def);
  }
  function strictObject(shape, params) {
    return new ZodObject(__spreadValues({
      type: "object",
      shape,
      catchall: never()
    }, normalizeParams(params)));
  }
  function looseObject(shape, params) {
    return new ZodObject(__spreadValues({
      type: "object",
      shape,
      catchall: unknown()
    }, normalizeParams(params)));
  }
  const ZodUnion = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => {
    $ZodUnion.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => unionProcessor(inst, ctx, json2, params);
    inst.options = def.options;
  });
  function union(options, params) {
    return new ZodUnion(__spreadValues({
      type: "union",
      options
    }, normalizeParams(params)));
  }
  const ZodXor = /* @__PURE__ */ $constructor("ZodXor", (inst, def) => {
    ZodUnion.init(inst, def);
    $ZodXor.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => unionProcessor(inst, ctx, json2, params);
    inst.options = def.options;
  });
  function xor(options, params) {
    return new ZodXor(__spreadValues({
      type: "union",
      options,
      inclusive: false
    }, normalizeParams(params)));
  }
  const ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def) => {
    ZodUnion.init(inst, def);
    $ZodDiscriminatedUnion.init(inst, def);
  });
  function discriminatedUnion(discriminator2, options, params) {
    return new ZodDiscriminatedUnion(__spreadValues({
      type: "union",
      options,
      discriminator: discriminator2
    }, normalizeParams(params)));
  }
  const ZodIntersection = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => {
    $ZodIntersection.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => intersectionProcessor(inst, ctx, json2, params);
  });
  function intersection(left, right) {
    return new ZodIntersection({
      type: "intersection",
      left,
      right
    });
  }
  const ZodTuple = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => {
    $ZodTuple.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => tupleProcessor(inst, ctx, json2, params);
    inst.rest = (rest) => inst.clone(__spreadProps(__spreadValues({}, inst._zod.def), {
      rest
    }));
  });
  function tuple(items2, _paramsOrRest, _params) {
    const hasRest = _paramsOrRest instanceof $ZodType;
    const params = hasRest ? _params : _paramsOrRest;
    const rest = hasRest ? _paramsOrRest : null;
    return new ZodTuple(__spreadValues({
      type: "tuple",
      items: items2,
      rest
    }, normalizeParams(params)));
  }
  const ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => {
    $ZodRecord.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => recordProcessor(inst, ctx, json2, params);
    inst.keyType = def.keyType;
    inst.valueType = def.valueType;
  });
  function record(keyType, valueType, params) {
    return new ZodRecord(__spreadValues({
      type: "record",
      keyType,
      valueType
    }, normalizeParams(params)));
  }
  function partialRecord(keyType, valueType, params) {
    const k = clone(keyType);
    k._zod.values = void 0;
    return new ZodRecord(__spreadValues({
      type: "record",
      keyType: k,
      valueType
    }, normalizeParams(params)));
  }
  function looseRecord(keyType, valueType, params) {
    return new ZodRecord(__spreadValues({
      type: "record",
      keyType,
      valueType,
      mode: "loose"
    }, normalizeParams(params)));
  }
  const ZodMap = /* @__PURE__ */ $constructor("ZodMap", (inst, def) => {
    $ZodMap.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => mapProcessor(inst, ctx);
    inst.keyType = def.keyType;
    inst.valueType = def.valueType;
  });
  function map(keyType, valueType, params) {
    return new ZodMap(__spreadValues({
      type: "map",
      keyType,
      valueType
    }, normalizeParams(params)));
  }
  const ZodSet = /* @__PURE__ */ $constructor("ZodSet", (inst, def) => {
    $ZodSet.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => setProcessor(inst, ctx);
    inst.min = (...args) => inst.check(_minSize(...args));
    inst.nonempty = (params) => inst.check(_minSize(1, params));
    inst.max = (...args) => inst.check(_maxSize(...args));
    inst.size = (...args) => inst.check(_size(...args));
  });
  function set(valueType, params) {
    return new ZodSet(__spreadValues({
      type: "set",
      valueType
    }, normalizeParams(params)));
  }
  const ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => {
    $ZodEnum.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => enumProcessor(inst, ctx, json2);
    inst.enum = def.entries;
    inst.options = Object.values(def.entries);
    const keys = new Set(Object.keys(def.entries));
    inst.extract = (values, params) => {
      const newEntries = {};
      for (const value of values) {
        if (keys.has(value)) {
          newEntries[value] = def.entries[value];
        } else
          throw new Error(`Key ${value} not found in enum`);
      }
      return new ZodEnum(__spreadProps(__spreadValues(__spreadProps(__spreadValues({}, def), {
        checks: []
      }), normalizeParams(params)), {
        entries: newEntries
      }));
    };
    inst.exclude = (values, params) => {
      const newEntries = __spreadValues({}, def.entries);
      for (const value of values) {
        if (keys.has(value)) {
          delete newEntries[value];
        } else
          throw new Error(`Key ${value} not found in enum`);
      }
      return new ZodEnum(__spreadProps(__spreadValues(__spreadProps(__spreadValues({}, def), {
        checks: []
      }), normalizeParams(params)), {
        entries: newEntries
      }));
    };
  });
  function _enum$1(values, params) {
    const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;
    return new ZodEnum(__spreadValues({
      type: "enum",
      entries
    }, normalizeParams(params)));
  }
  function nativeEnum(entries, params) {
    return new ZodEnum(__spreadValues({
      type: "enum",
      entries
    }, normalizeParams(params)));
  }
  const ZodLiteral = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => {
    $ZodLiteral.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => literalProcessor(inst, ctx, json2);
    inst.values = new Set(def.values);
    Object.defineProperty(inst, "value", {
      get() {
        if (def.values.length > 1) {
          throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");
        }
        return def.values[0];
      }
    });
  });
  function literal(value, params) {
    return new ZodLiteral(__spreadValues({
      type: "literal",
      values: Array.isArray(value) ? value : [value]
    }, normalizeParams(params)));
  }
  const ZodFile = /* @__PURE__ */ $constructor("ZodFile", (inst, def) => {
    $ZodFile.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => fileProcessor(inst, ctx, json2);
    inst.min = (size, params) => inst.check(_minSize(size, params));
    inst.max = (size, params) => inst.check(_maxSize(size, params));
    inst.mime = (types2, params) => inst.check(_mime(Array.isArray(types2) ? types2 : [types2], params));
  });
  function file(params) {
    return _file(ZodFile, params);
  }
  const ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => {
    $ZodTransform.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => transformProcessor(inst, ctx);
    inst._zod.parse = (payload, _ctx) => {
      if (_ctx.direction === "backward") {
        throw new $ZodEncodeError(inst.constructor.name);
      }
      payload.addIssue = (issue$1) => {
        var _a3, _b2, _c2;
        if (typeof issue$1 === "string") {
          payload.issues.push(issue(issue$1, payload.value, def));
        } else {
          const _issue = issue$1;
          if (_issue.fatal)
            _issue.continue = false;
          (_a3 = _issue.code) != null ? _a3 : _issue.code = "custom";
          (_b2 = _issue.input) != null ? _b2 : _issue.input = payload.value;
          (_c2 = _issue.inst) != null ? _c2 : _issue.inst = inst;
          payload.issues.push(issue(_issue));
        }
      };
      const output = def.transform(payload.value, payload);
      if (output instanceof Promise) {
        return output.then((output2) => {
          payload.value = output2;
          return payload;
        });
      }
      payload.value = output;
      return payload;
    };
  });
  function transform(fn) {
    return new ZodTransform({
      type: "transform",
      transform: fn
    });
  }
  const ZodOptional = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => {
    $ZodOptional.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => optionalProcessor(inst, ctx, json2, params);
    inst.unwrap = () => inst._zod.def.innerType;
  });
  function optional(innerType) {
    return new ZodOptional({
      type: "optional",
      innerType
    });
  }
  const ZodNullable = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => {
    $ZodNullable.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => nullableProcessor(inst, ctx, json2, params);
    inst.unwrap = () => inst._zod.def.innerType;
  });
  function nullable(innerType) {
    return new ZodNullable({
      type: "nullable",
      innerType
    });
  }
  function nullish(innerType) {
    return optional(nullable(innerType));
  }
  const ZodDefault = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => {
    $ZodDefault.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => defaultProcessor(inst, ctx, json2, params);
    inst.unwrap = () => inst._zod.def.innerType;
    inst.removeDefault = inst.unwrap;
  });
  function _default(innerType, defaultValue) {
    return new ZodDefault({
      type: "default",
      innerType,
      get defaultValue() {
        return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
      }
    });
  }
  const ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => {
    $ZodPrefault.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => prefaultProcessor(inst, ctx, json2, params);
    inst.unwrap = () => inst._zod.def.innerType;
  });
  function prefault(innerType, defaultValue) {
    return new ZodPrefault({
      type: "prefault",
      innerType,
      get defaultValue() {
        return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
      }
    });
  }
  const ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => {
    $ZodNonOptional.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => nonoptionalProcessor(inst, ctx, json2, params);
    inst.unwrap = () => inst._zod.def.innerType;
  });
  function nonoptional(innerType, params) {
    return new ZodNonOptional(__spreadValues({
      type: "nonoptional",
      innerType
    }, normalizeParams(params)));
  }
  const ZodSuccess = /* @__PURE__ */ $constructor("ZodSuccess", (inst, def) => {
    $ZodSuccess.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => successProcessor(inst, ctx, json2);
    inst.unwrap = () => inst._zod.def.innerType;
  });
  function success(innerType) {
    return new ZodSuccess({
      type: "success",
      innerType
    });
  }
  const ZodCatch = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => {
    $ZodCatch.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => catchProcessor(inst, ctx, json2, params);
    inst.unwrap = () => inst._zod.def.innerType;
    inst.removeCatch = inst.unwrap;
  });
  function _catch(innerType, catchValue) {
    return new ZodCatch({
      type: "catch",
      innerType,
      catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
    });
  }
  const ZodNaN = /* @__PURE__ */ $constructor("ZodNaN", (inst, def) => {
    $ZodNaN.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => nanProcessor(inst, ctx);
  });
  function nan(params) {
    return _nan(ZodNaN, params);
  }
  const ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => {
    $ZodPipe.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => pipeProcessor(inst, ctx, json2, params);
    inst.in = def.in;
    inst.out = def.out;
  });
  function pipe(in_, out) {
    return new ZodPipe({
      type: "pipe",
      in: in_,
      out
      // ...util.normalizeParams(params),
    });
  }
  const ZodCodec = /* @__PURE__ */ $constructor("ZodCodec", (inst, def) => {
    ZodPipe.init(inst, def);
    $ZodCodec.init(inst, def);
  });
  function codec(in_, out, params) {
    return new ZodCodec({
      type: "pipe",
      in: in_,
      out,
      transform: params.decode,
      reverseTransform: params.encode
    });
  }
  const ZodReadonly = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => {
    $ZodReadonly.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => readonlyProcessor(inst, ctx, json2, params);
    inst.unwrap = () => inst._zod.def.innerType;
  });
  function readonly(innerType) {
    return new ZodReadonly({
      type: "readonly",
      innerType
    });
  }
  const ZodTemplateLiteral = /* @__PURE__ */ $constructor("ZodTemplateLiteral", (inst, def) => {
    $ZodTemplateLiteral.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => templateLiteralProcessor(inst, ctx, json2);
  });
  function templateLiteral(parts, params) {
    return new ZodTemplateLiteral(__spreadValues({
      type: "template_literal",
      parts
    }, normalizeParams(params)));
  }
  const ZodLazy = /* @__PURE__ */ $constructor("ZodLazy", (inst, def) => {
    $ZodLazy.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => lazyProcessor(inst, ctx, json2, params);
    inst.unwrap = () => inst._zod.def.getter();
  });
  function lazy(getter) {
    return new ZodLazy({
      type: "lazy",
      getter
    });
  }
  const ZodPromise = /* @__PURE__ */ $constructor("ZodPromise", (inst, def) => {
    $ZodPromise.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => promiseProcessor(inst, ctx, json2, params);
    inst.unwrap = () => inst._zod.def.innerType;
  });
  function promise(innerType) {
    return new ZodPromise({
      type: "promise",
      innerType
    });
  }
  const ZodFunction = /* @__PURE__ */ $constructor("ZodFunction", (inst, def) => {
    $ZodFunction.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => functionProcessor(inst, ctx);
  });
  function _function(params) {
    var _a3, _b2;
    return new ZodFunction({
      type: "function",
      input: Array.isArray(params == null ? void 0 : params.input) ? tuple(params == null ? void 0 : params.input) : (_a3 = params == null ? void 0 : params.input) != null ? _a3 : array(unknown()),
      output: (_b2 = params == null ? void 0 : params.output) != null ? _b2 : unknown()
    });
  }
  const ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => {
    $ZodCustom.init(inst, def);
    ZodType.init(inst, def);
    inst._zod.processJSONSchema = (ctx, json2, params) => customProcessor(inst, ctx);
  });
  function check(fn) {
    const ch = new $ZodCheck({
      check: "custom"
      // ...util.normalizeParams(params),
    });
    ch._zod.check = fn;
    return ch;
  }
  function custom(fn, _params) {
    return _custom(ZodCustom, fn != null ? fn : (() => true), _params);
  }
  function refine(fn, _params = {}) {
    return _refine(ZodCustom, fn, _params);
  }
  function superRefine(fn) {
    return _superRefine(fn);
  }
  const describe = describe$1;
  const meta = meta$1;
  function _instanceof(cls, params = {
    error: `Input not instance of ${cls.name}`
  }) {
    const inst = new ZodCustom(__spreadValues({
      type: "custom",
      check: "custom",
      fn: (data) => data instanceof cls,
      abort: true
    }, normalizeParams(params)));
    inst._zod.bag.Class = cls;
    return inst;
  }
  const stringbool = (...args) => _stringbool({
    Codec: ZodCodec,
    Boolean: ZodBoolean,
    String: ZodString
  }, ...args);
  function json(params) {
    const jsonSchema2 = lazy(() => {
      return union([string$1(params), number$1(), boolean$1(), _null(), array(jsonSchema2), record(string$1(), jsonSchema2)]);
    });
    return jsonSchema2;
  }
  function preprocess(fn, schema) {
    return pipe(transform(fn), schema);
  }
  const _schemas = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
    __proto__: null,
    ZodAny,
    ZodArray,
    ZodBase64,
    ZodBase64URL,
    ZodBigInt,
    ZodBigIntFormat,
    ZodBoolean,
    ZodCIDRv4,
    ZodCIDRv6,
    ZodCUID,
    ZodCUID2,
    ZodCatch,
    ZodCodec,
    ZodCustom,
    ZodCustomStringFormat,
    ZodDate,
    ZodDefault,
    ZodDiscriminatedUnion,
    ZodE164,
    ZodEmail,
    ZodEmoji,
    ZodEnum,
    ZodFile,
    ZodFunction,
    ZodGUID,
    ZodIPv4,
    ZodIPv6,
    ZodIntersection,
    ZodJWT,
    ZodKSUID,
    ZodLazy,
    ZodLiteral,
    ZodMAC,
    ZodMap,
    ZodNaN,
    ZodNanoID,
    ZodNever,
    ZodNonOptional,
    ZodNull,
    ZodNullable,
    ZodNumber,
    ZodNumberFormat,
    ZodObject,
    ZodOptional,
    ZodPipe,
    ZodPrefault,
    ZodPromise,
    ZodReadonly,
    ZodRecord,
    ZodSet,
    ZodString,
    ZodStringFormat,
    ZodSuccess,
    ZodSymbol,
    ZodTemplateLiteral,
    ZodTransform,
    ZodTuple,
    ZodType,
    ZodULID,
    ZodURL,
    ZodUUID,
    ZodUndefined,
    ZodUnion,
    ZodUnknown,
    ZodVoid,
    ZodXID,
    ZodXor,
    _ZodString,
    _default,
    _function,
    any,
    array,
    base64,
    base64url,
    bigint: bigint$1,
    boolean: boolean$1,
    catch: _catch,
    check,
    cidrv4,
    cidrv6,
    codec,
    cuid,
    cuid2,
    custom,
    date: date$1,
    describe,
    discriminatedUnion,
    e164,
    email,
    emoji,
    enum: _enum$1,
    file,
    float32,
    float64,
    function: _function,
    guid,
    hash,
    hex,
    hostname,
    httpUrl,
    instanceof: _instanceof,
    int,
    int32,
    int64,
    intersection,
    ipv4,
    ipv6,
    json,
    jwt,
    keyof,
    ksuid,
    lazy,
    literal,
    looseObject,
    looseRecord,
    mac,
    map,
    meta,
    nan,
    nanoid: nanoid$1,
    nativeEnum,
    never,
    nonoptional,
    null: _null,
    nullable,
    nullish,
    number: number$1,
    object,
    optional,
    partialRecord,
    pipe,
    prefault,
    preprocess,
    promise,
    readonly,
    record,
    refine,
    set,
    strictObject,
    string: string$1,
    stringFormat,
    stringbool,
    success,
    superRefine,
    symbol,
    templateLiteral,
    transform,
    tuple,
    uint32,
    uint64,
    ulid,
    undefined: _undefined,
    union,
    unknown,
    url,
    uuid,
    uuidv4,
    uuidv6,
    uuidv7,
    void: _void,
    xid,
    xor
  }, Symbol.toStringTag, { value: "Module" }));
  const ZodIssueCode = {
    invalid_type: "invalid_type",
    too_big: "too_big",
    too_small: "too_small",
    invalid_format: "invalid_format",
    not_multiple_of: "not_multiple_of",
    unrecognized_keys: "unrecognized_keys",
    invalid_union: "invalid_union",
    invalid_key: "invalid_key",
    invalid_element: "invalid_element",
    invalid_value: "invalid_value",
    custom: "custom"
  };
  function setErrorMap(map2) {
    config({
      customError: map2
    });
  }
  function getErrorMap() {
    return config().customError;
  }
  var ZodFirstPartyTypeKind;
  /* @__PURE__ */ (function(ZodFirstPartyTypeKind2) {
  })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
  const z = __spreadProps(__spreadValues(__spreadValues({}, _schemas), _checks), {
    iso: _iso
  });
  function detectVersion(schema, defaultTarget) {
    const $schema2 = schema.$schema;
    if ($schema2 === "https://json-schema.org/draft/2020-12/schema") {
      return "draft-2020-12";
    }
    if ($schema2 === "http://json-schema.org/draft-07/schema#") {
      return "draft-7";
    }
    if ($schema2 === "http://json-schema.org/draft-04/schema#") {
      return "draft-4";
    }
    return defaultTarget != null ? defaultTarget : "draft-2020-12";
  }
  function resolveRef(ref2, ctx) {
    if (!ref2.startsWith("#")) {
      throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
    }
    const path = ref2.slice(1).split("/").filter(Boolean);
    if (path.length === 0) {
      return ctx.rootSchema;
    }
    const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
    if (path[0] === defsKey) {
      const key = path[1];
      if (!key || !ctx.defs[key]) {
        throw new Error(`Reference not found: ${ref2}`);
      }
      return ctx.defs[key];
    }
    throw new Error(`Reference not found: ${ref2}`);
  }
  function convertBaseSchema(schema, ctx) {
    if (schema.not !== void 0) {
      if (typeof schema.not === "object" && Object.keys(schema.not).length === 0) {
        return z.never();
      }
      throw new Error("not is not supported in Zod (except { not: {} } for never)");
    }
    if (schema.unevaluatedItems !== void 0) {
      throw new Error("unevaluatedItems is not supported");
    }
    if (schema.unevaluatedProperties !== void 0) {
      throw new Error("unevaluatedProperties is not supported");
    }
    if (schema.if !== void 0 || schema.then !== void 0 || schema.else !== void 0) {
      throw new Error("Conditional schemas (if/then/else) are not supported");
    }
    if (schema.dependentSchemas !== void 0 || schema.dependentRequired !== void 0) {
      throw new Error("dependentSchemas and dependentRequired are not supported");
    }
    if (schema.$ref) {
      const refPath = schema.$ref;
      if (ctx.refs.has(refPath)) {
        return ctx.refs.get(refPath);
      }
      if (ctx.processing.has(refPath)) {
        return z.lazy(() => {
          if (!ctx.refs.has(refPath)) {
            throw new Error(`Circular reference not resolved: ${refPath}`);
          }
          return ctx.refs.get(refPath);
        });
      }
      ctx.processing.add(refPath);
      const resolved = resolveRef(refPath, ctx);
      const zodSchema2 = convertSchema(resolved, ctx);
      ctx.refs.set(refPath, zodSchema2);
      ctx.processing.delete(refPath);
      return zodSchema2;
    }
    if (schema.enum !== void 0) {
      const enumValues = schema.enum;
      if (ctx.version === "openapi-3.0" && schema.nullable === true && enumValues.length === 1 && enumValues[0] === null) {
        return z.null();
      }
      if (enumValues.length === 0) {
        return z.never();
      }
      if (enumValues.length === 1) {
        return z.literal(enumValues[0]);
      }
      if (enumValues.every((v) => typeof v === "string")) {
        return z.enum(enumValues);
      }
      const literalSchemas = enumValues.map((v) => z.literal(v));
      if (literalSchemas.length < 2) {
        return literalSchemas[0];
      }
      return z.union([literalSchemas[0], literalSchemas[1], ...literalSchemas.slice(2)]);
    }
    if (schema.const !== void 0) {
      return z.literal(schema.const);
    }
    const type2 = schema.type;
    if (Array.isArray(type2)) {
      const typeSchemas = type2.map((t) => {
        const typeSchema = __spreadProps(__spreadValues({}, schema), { type: t });
        return convertBaseSchema(typeSchema, ctx);
      });
      if (typeSchemas.length === 0) {
        return z.never();
      }
      if (typeSchemas.length === 1) {
        return typeSchemas[0];
      }
      return z.union(typeSchemas);
    }
    if (!type2) {
      return z.any();
    }
    let zodSchema;
    switch (type2) {
      case "string": {
        let stringSchema = z.string();
        if (schema.format) {
          const format2 = schema.format;
          if (format2 === "email") {
            stringSchema = stringSchema.check(z.email());
          } else if (format2 === "uri" || format2 === "uri-reference") {
            stringSchema = stringSchema.check(z.url());
          } else if (format2 === "uuid" || format2 === "guid") {
            stringSchema = stringSchema.check(z.uuid());
          } else if (format2 === "date-time") {
            stringSchema = stringSchema.check(z.iso.datetime());
          } else if (format2 === "date") {
            stringSchema = stringSchema.check(z.iso.date());
          } else if (format2 === "time") {
            stringSchema = stringSchema.check(z.iso.time());
          } else if (format2 === "duration") {
            stringSchema = stringSchema.check(z.iso.duration());
          } else if (format2 === "ipv4") {
            stringSchema = stringSchema.check(z.ipv4());
          } else if (format2 === "ipv6") {
            stringSchema = stringSchema.check(z.ipv6());
          } else if (format2 === "mac") {
            stringSchema = stringSchema.check(z.mac());
          } else if (format2 === "cidr") {
            stringSchema = stringSchema.check(z.cidrv4());
          } else if (format2 === "cidr-v6") {
            stringSchema = stringSchema.check(z.cidrv6());
          } else if (format2 === "base64") {
            stringSchema = stringSchema.check(z.base64());
          } else if (format2 === "base64url") {
            stringSchema = stringSchema.check(z.base64url());
          } else if (format2 === "e164") {
            stringSchema = stringSchema.check(z.e164());
          } else if (format2 === "jwt") {
            stringSchema = stringSchema.check(z.jwt());
          } else if (format2 === "emoji") {
            stringSchema = stringSchema.check(z.emoji());
          } else if (format2 === "nanoid") {
            stringSchema = stringSchema.check(z.nanoid());
          } else if (format2 === "cuid") {
            stringSchema = stringSchema.check(z.cuid());
          } else if (format2 === "cuid2") {
            stringSchema = stringSchema.check(z.cuid2());
          } else if (format2 === "ulid") {
            stringSchema = stringSchema.check(z.ulid());
          } else if (format2 === "xid") {
            stringSchema = stringSchema.check(z.xid());
          } else if (format2 === "ksuid") {
            stringSchema = stringSchema.check(z.ksuid());
          }
        }
        if (typeof schema.minLength === "number") {
          stringSchema = stringSchema.min(schema.minLength);
        }
        if (typeof schema.maxLength === "number") {
          stringSchema = stringSchema.max(schema.maxLength);
        }
        if (schema.pattern) {
          stringSchema = stringSchema.regex(new RegExp(schema.pattern));
        }
        zodSchema = stringSchema;
        break;
      }
      case "number":
      case "integer": {
        let numberSchema = type2 === "integer" ? z.number().int() : z.number();
        if (typeof schema.minimum === "number") {
          numberSchema = numberSchema.min(schema.minimum);
        }
        if (typeof schema.maximum === "number") {
          numberSchema = numberSchema.max(schema.maximum);
        }
        if (typeof schema.exclusiveMinimum === "number") {
          numberSchema = numberSchema.gt(schema.exclusiveMinimum);
        } else if (schema.exclusiveMinimum === true && typeof schema.minimum === "number") {
          numberSchema = numberSchema.gt(schema.minimum);
        }
        if (typeof schema.exclusiveMaximum === "number") {
          numberSchema = numberSchema.lt(schema.exclusiveMaximum);
        } else if (schema.exclusiveMaximum === true && typeof schema.maximum === "number") {
          numberSchema = numberSchema.lt(schema.maximum);
        }
        if (typeof schema.multipleOf === "number") {
          numberSchema = numberSchema.multipleOf(schema.multipleOf);
        }
        zodSchema = numberSchema;
        break;
      }
      case "boolean": {
        zodSchema = z.boolean();
        break;
      }
      case "null": {
        zodSchema = z.null();
        break;
      }
      case "object": {
        const shape = {};
        const properties2 = schema.properties || {};
        const requiredSet = new Set(schema.required || []);
        for (const [key, propSchema] of Object.entries(properties2)) {
          const propZodSchema = convertSchema(propSchema, ctx);
          shape[key] = requiredSet.has(key) ? propZodSchema : propZodSchema.optional();
        }
        if (schema.propertyNames) {
          const keySchema = convertSchema(schema.propertyNames, ctx);
          const valueSchema = schema.additionalProperties && typeof schema.additionalProperties === "object" ? convertSchema(schema.additionalProperties, ctx) : z.any();
          if (Object.keys(shape).length === 0) {
            zodSchema = z.record(keySchema, valueSchema);
            break;
          }
          const objectSchema2 = z.object(shape).passthrough();
          const recordSchema = z.looseRecord(keySchema, valueSchema);
          zodSchema = z.intersection(objectSchema2, recordSchema);
          break;
        }
        if (schema.patternProperties) {
          const patternProps = schema.patternProperties;
          const patternKeys = Object.keys(patternProps);
          const looseRecords = [];
          for (const pattern2 of patternKeys) {
            const patternValue = convertSchema(patternProps[pattern2], ctx);
            const keySchema = z.string().regex(new RegExp(pattern2));
            looseRecords.push(z.looseRecord(keySchema, patternValue));
          }
          const schemasToIntersect = [];
          if (Object.keys(shape).length > 0) {
            schemasToIntersect.push(z.object(shape).passthrough());
          }
          schemasToIntersect.push(...looseRecords);
          if (schemasToIntersect.length === 0) {
            zodSchema = z.object({}).passthrough();
          } else if (schemasToIntersect.length === 1) {
            zodSchema = schemasToIntersect[0];
          } else {
            let result2 = z.intersection(schemasToIntersect[0], schemasToIntersect[1]);
            for (let i2 = 2; i2 < schemasToIntersect.length; i2++) {
              result2 = z.intersection(result2, schemasToIntersect[i2]);
            }
            zodSchema = result2;
          }
          break;
        }
        const objectSchema = z.object(shape);
        if (schema.additionalProperties === false) {
          zodSchema = objectSchema.strict();
        } else if (typeof schema.additionalProperties === "object") {
          zodSchema = objectSchema.catchall(convertSchema(schema.additionalProperties, ctx));
        } else {
          zodSchema = objectSchema.passthrough();
        }
        break;
      }
      case "array": {
        const prefixItems2 = schema.prefixItems;
        const items2 = schema.items;
        if (prefixItems2 && Array.isArray(prefixItems2)) {
          const tupleItems = prefixItems2.map((item) => convertSchema(item, ctx));
          const rest = items2 && typeof items2 === "object" && !Array.isArray(items2) ? convertSchema(items2, ctx) : void 0;
          if (rest) {
            zodSchema = z.tuple(tupleItems).rest(rest);
          } else {
            zodSchema = z.tuple(tupleItems);
          }
          if (typeof schema.minItems === "number") {
            zodSchema = zodSchema.check(z.minLength(schema.minItems));
          }
          if (typeof schema.maxItems === "number") {
            zodSchema = zodSchema.check(z.maxLength(schema.maxItems));
          }
        } else if (Array.isArray(items2)) {
          const tupleItems = items2.map((item) => convertSchema(item, ctx));
          const rest = schema.additionalItems && typeof schema.additionalItems === "object" ? convertSchema(schema.additionalItems, ctx) : void 0;
          if (rest) {
            zodSchema = z.tuple(tupleItems).rest(rest);
          } else {
            zodSchema = z.tuple(tupleItems);
          }
          if (typeof schema.minItems === "number") {
            zodSchema = zodSchema.check(z.minLength(schema.minItems));
          }
          if (typeof schema.maxItems === "number") {
            zodSchema = zodSchema.check(z.maxLength(schema.maxItems));
          }
        } else if (items2 !== void 0) {
          const element = convertSchema(items2, ctx);
          let arraySchema = z.array(element);
          if (typeof schema.minItems === "number") {
            arraySchema = arraySchema.min(schema.minItems);
          }
          if (typeof schema.maxItems === "number") {
            arraySchema = arraySchema.max(schema.maxItems);
          }
          zodSchema = arraySchema;
        } else {
          zodSchema = z.array(z.any());
        }
        break;
      }
      default:
        throw new Error(`Unsupported type: ${type2}`);
    }
    if (schema.description) {
      zodSchema = zodSchema.describe(schema.description);
    }
    if (schema.default !== void 0) {
      zodSchema = zodSchema.default(schema.default);
    }
    return zodSchema;
  }
  function convertSchema(schema, ctx) {
    if (typeof schema === "boolean") {
      return schema ? z.any() : z.never();
    }
    let baseSchema = convertBaseSchema(schema, ctx);
    const hasExplicitType = schema.type || schema.enum !== void 0 || schema.const !== void 0;
    if (schema.anyOf && Array.isArray(schema.anyOf)) {
      const options = schema.anyOf.map((s) => convertSchema(s, ctx));
      const anyOfUnion = z.union(options);
      baseSchema = hasExplicitType ? z.intersection(baseSchema, anyOfUnion) : anyOfUnion;
    }
    if (schema.oneOf && Array.isArray(schema.oneOf)) {
      const options = schema.oneOf.map((s) => convertSchema(s, ctx));
      const oneOfUnion = z.xor(options);
      baseSchema = hasExplicitType ? z.intersection(baseSchema, oneOfUnion) : oneOfUnion;
    }
    if (schema.allOf && Array.isArray(schema.allOf)) {
      if (schema.allOf.length === 0) {
        baseSchema = hasExplicitType ? baseSchema : z.any();
      } else {
        let result2 = hasExplicitType ? baseSchema : convertSchema(schema.allOf[0], ctx);
        const startIdx = hasExplicitType ? 0 : 1;
        for (let i2 = startIdx; i2 < schema.allOf.length; i2++) {
          result2 = z.intersection(result2, convertSchema(schema.allOf[i2], ctx));
        }
        baseSchema = result2;
      }
    }
    if (schema.nullable === true && ctx.version === "openapi-3.0") {
      baseSchema = z.nullable(baseSchema);
    }
    if (schema.readOnly === true) {
      baseSchema = z.readonly(baseSchema);
    }
    return baseSchema;
  }
  function fromJSONSchema(schema, params) {
    if (typeof schema === "boolean") {
      return schema ? z.any() : z.never();
    }
    const version2 = detectVersion(schema, params == null ? void 0 : params.defaultTarget);
    const defs = schema.$defs || schema.definitions || {};
    const ctx = {
      version: version2,
      defs,
      refs: /* @__PURE__ */ new Map(),
      processing: /* @__PURE__ */ new Set(),
      rootSchema: schema
    };
    return convertSchema(schema, ctx);
  }
  function string(params) {
    return _coercedString(ZodString, params);
  }
  function number(params) {
    return _coercedNumber(ZodNumber, params);
  }
  function boolean(params) {
    return _coercedBoolean(ZodBoolean, params);
  }
  function bigint(params) {
    return _coercedBigint(ZodBigInt, params);
  }
  function date(params) {
    return _coercedDate(ZodDate, params);
  }
  const coerce = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
    __proto__: null,
    bigint,
    boolean,
    date,
    number,
    string
  }, Symbol.toStringTag, { value: "Module" }));
  config(en());
  const zod = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
    __proto__: null,
    $brand,
    $input,
    $output,
    NEVER,
    TimePrecision,
    ZodAny,
    ZodArray,
    ZodBase64,
    ZodBase64URL,
    ZodBigInt,
    ZodBigIntFormat,
    ZodBoolean,
    ZodCIDRv4,
    ZodCIDRv6,
    ZodCUID,
    ZodCUID2,
    ZodCatch,
    ZodCodec,
    ZodCustom,
    ZodCustomStringFormat,
    ZodDate,
    ZodDefault,
    ZodDiscriminatedUnion,
    ZodE164,
    ZodEmail,
    ZodEmoji,
    ZodEnum,
    ZodError,
    ZodFile,
    get ZodFirstPartyTypeKind() {
      return ZodFirstPartyTypeKind;
    },
    ZodFunction,
    ZodGUID,
    ZodIPv4,
    ZodIPv6,
    ZodISODate,
    ZodISODateTime,
    ZodISODuration,
    ZodISOTime,
    ZodIntersection,
    ZodIssueCode,
    ZodJWT,
    ZodKSUID,
    ZodLazy,
    ZodLiteral,
    ZodMAC,
    ZodMap,
    ZodNaN,
    ZodNanoID,
    ZodNever,
    ZodNonOptional,
    ZodNull,
    ZodNullable,
    ZodNumber,
    ZodNumberFormat,
    ZodObject,
    ZodOptional,
    ZodPipe,
    ZodPrefault,
    ZodPromise,
    ZodReadonly,
    ZodRealError,
    ZodRecord,
    ZodSet,
    ZodString,
    ZodStringFormat,
    ZodSuccess,
    ZodSymbol,
    ZodTemplateLiteral,
    ZodTransform,
    ZodTuple,
    ZodType,
    ZodULID,
    ZodURL,
    ZodUUID,
    ZodUndefined,
    ZodUnion,
    ZodUnknown,
    ZodVoid,
    ZodXID,
    ZodXor,
    _ZodString,
    _default,
    _function,
    any,
    array,
    base64,
    base64url,
    bigint: bigint$1,
    boolean: boolean$1,
    catch: _catch,
    check,
    cidrv4,
    cidrv6,
    clone,
    codec,
    coerce,
    config,
    core: index$4,
    cuid,
    cuid2,
    custom,
    date: date$1,
    decode,
    decodeAsync,
    describe,
    discriminatedUnion,
    e164,
    email,
    emoji,
    encode,
    encodeAsync,
    endsWith: _endsWith,
    enum: _enum$1,
    file,
    flattenError,
    float32,
    float64,
    formatError,
    fromJSONSchema,
    function: _function,
    getErrorMap,
    globalRegistry,
    gt: _gt,
    gte: _gte,
    guid,
    hash,
    hex,
    hostname,
    httpUrl,
    includes: _includes,
    instanceof: _instanceof,
    int,
    int32,
    int64,
    intersection,
    ipv4,
    ipv6,
    iso: _iso,
    json,
    jwt,
    keyof,
    ksuid,
    lazy,
    length: _length,
    literal,
    locales: index$5,
    looseObject,
    looseRecord,
    lowercase: _lowercase,
    lt: _lt,
    lte: _lte,
    mac,
    map,
    maxLength: _maxLength,
    maxSize: _maxSize,
    meta,
    mime: _mime,
    minLength: _minLength,
    minSize: _minSize,
    multipleOf: _multipleOf,
    nan,
    nanoid: nanoid$1,
    nativeEnum,
    negative: _negative,
    never,
    nonnegative: _nonnegative,
    nonoptional,
    nonpositive: _nonpositive,
    normalize: _normalize,
    null: _null,
    nullable,
    nullish,
    number: number$1,
    object,
    optional,
    overwrite: _overwrite,
    parse,
    parseAsync,
    partialRecord,
    pipe,
    positive: _positive,
    prefault,
    preprocess,
    prettifyError,
    promise,
    property: _property,
    readonly,
    record,
    refine,
    regex: _regex,
    regexes,
    registry,
    safeDecode,
    safeDecodeAsync,
    safeEncode,
    safeEncodeAsync,
    safeParse,
    safeParseAsync,
    set,
    setErrorMap,
    size: _size,
    slugify: _slugify,
    startsWith: _startsWith,
    strictObject,
    string: string$1,
    stringFormat,
    stringbool,
    success,
    superRefine,
    symbol,
    templateLiteral,
    toJSONSchema,
    toLowerCase: _toLowerCase,
    toUpperCase: _toUpperCase,
    transform,
    treeifyError,
    trim: _trim,
    tuple,
    uint32,
    uint64,
    ulid,
    undefined: _undefined,
    union,
    unknown,
    uppercase: _uppercase,
    url,
    util: util$1,
    uuid,
    uuidv4,
    uuidv6,
    uuidv7,
    void: _void,
    xid,
    xor
  }, Symbol.toStringTag, { value: "Module" }));
  const LATEST_PROTOCOL_VERSION = "2025-11-25";
  const SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, "2025-06-18", "2025-03-26", "2024-11-05", "2024-10-07"];
  const RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task";
  const JSONRPC_VERSION = "2.0";
  const AssertObjectSchema = custom((v) => v !== null && (typeof v === "object" || typeof v === "function"));
  const ProgressTokenSchema = union([string$1(), number$1().int()]);
  const CursorSchema = string$1();
  looseObject({
    /**
     * Time in milliseconds to keep task results available after completion.
     * If null, the task has unlimited lifetime until manually cleaned up.
     */
    ttl: union([number$1(), _null()]).optional(),
    /**
     * Time in milliseconds to wait between task status requests.
     */
    pollInterval: number$1().optional()
  });
  const TaskMetadataSchema = object({
    ttl: number$1().optional()
  });
  const RelatedTaskMetadataSchema = object({
    taskId: string$1()
  });
  const RequestMetaSchema = looseObject({
    /**
     * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.
     */
    progressToken: ProgressTokenSchema.optional(),
    /**
     * If specified, this request is related to the provided task.
     */
    [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional()
  });
  const BaseRequestParamsSchema = object({
    /**
     * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage.
     */
    _meta: RequestMetaSchema.optional()
  });
  const TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({
    /**
     * If specified, the caller is requesting task-augmented execution for this request.
     * The request will return a CreateTaskResult immediately, and the actual result can be
     * retrieved later via tasks/result.
     *
     * Task augmentation is subject to capability negotiation - receivers MUST declare support
     * for task augmentation of specific request types in their capabilities.
     */
    task: TaskMetadataSchema.optional()
  });
  const isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success;
  const RequestSchema = object({
    method: string$1(),
    params: BaseRequestParamsSchema.loose().optional()
  });
  const NotificationsParamsSchema = object({
    /**
     * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
     * for notes on _meta usage.
     */
    _meta: RequestMetaSchema.optional()
  });
  const NotificationSchema = object({
    method: string$1(),
    params: NotificationsParamsSchema.loose().optional()
  });
  const ResultSchema = looseObject({
    /**
     * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
     * for notes on _meta usage.
     */
    _meta: RequestMetaSchema.optional()
  });
  const RequestIdSchema = union([string$1(), number$1().int()]);
  const JSONRPCRequestSchema = object(__spreadValues({
    jsonrpc: literal(JSONRPC_VERSION),
    id: RequestIdSchema
  }, RequestSchema.shape)).strict();
  const isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success;
  const JSONRPCNotificationSchema = object(__spreadValues({
    jsonrpc: literal(JSONRPC_VERSION)
  }, NotificationSchema.shape)).strict();
  const isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success;
  const JSONRPCResultResponseSchema = object({
    jsonrpc: literal(JSONRPC_VERSION),
    id: RequestIdSchema,
    result: ResultSchema
  }).strict();
  const isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success;
  var ErrorCode;
  (function(ErrorCode2) {
    ErrorCode2[ErrorCode2["ConnectionClosed"] = -32e3] = "ConnectionClosed";
    ErrorCode2[ErrorCode2["RequestTimeout"] = -32001] = "RequestTimeout";
    ErrorCode2[ErrorCode2["ParseError"] = -32700] = "ParseError";
    ErrorCode2[ErrorCode2["InvalidRequest"] = -32600] = "InvalidRequest";
    ErrorCode2[ErrorCode2["MethodNotFound"] = -32601] = "MethodNotFound";
    ErrorCode2[ErrorCode2["InvalidParams"] = -32602] = "InvalidParams";
    ErrorCode2[ErrorCode2["InternalError"] = -32603] = "InternalError";
    ErrorCode2[ErrorCode2["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired";
  })(ErrorCode || (ErrorCode = {}));
  const JSONRPCErrorResponseSchema = object({
    jsonrpc: literal(JSONRPC_VERSION),
    id: RequestIdSchema.optional(),
    error: object({
      /**
       * The error type that occurred.
       */
      code: number$1().int(),
      /**
       * A short description of the error. The message SHOULD be limited to a concise single sentence.
       */
      message: string$1(),
      /**
       * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.).
       */
      data: unknown().optional()
    })
  }).strict();
  const isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success;
  union([
    JSONRPCRequestSchema,
    JSONRPCNotificationSchema,
    JSONRPCResultResponseSchema,
    JSONRPCErrorResponseSchema
  ]);
  union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]);
  const EmptyResultSchema = ResultSchema.strict();
  const CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({
    /**
     * The ID of the request to cancel.
     *
     * This MUST correspond to the ID of a request previously issued in the same direction.
     */
    requestId: RequestIdSchema.optional(),
    /**
     * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.
     */
    reason: string$1().optional()
  });
  const CancelledNotificationSchema = NotificationSchema.extend({
    method: literal("notifications/cancelled"),
    params: CancelledNotificationParamsSchema
  });
  const IconSchema = object({
    /**
     * URL or data URI for the icon.
     */
    src: string$1(),
    /**
     * Optional MIME type for the icon.
     */
    mimeType: string$1().optional(),
    /**
     * Optional array of strings that specify sizes at which the icon can be used.
     * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG.
     *
     * If not provided, the client should assume that the icon can be used at any size.
     */
    sizes: array(string$1()).optional(),
    /**
     * Optional specifier for the theme this icon is designed for. `light` indicates
     * the icon is designed to be used with a light background, and `dark` indicates
     * the icon is designed to be used with a dark background.
     *
     * If not provided, the client should assume the icon can be used with any theme.
     */
    theme: _enum$1(["light", "dark"]).optional()
  });
  const IconsSchema = object({
    /**
     * Optional set of sized icons that the client can display in a user interface.
     *
     * Clients that support rendering icons MUST support at least the following MIME types:
     * - `image/png` - PNG images (safe, universal compatibility)
     * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)
     *
     * Clients that support rendering icons SHOULD also support:
     * - `image/svg+xml` - SVG images (scalable but requires security precautions)
     * - `image/webp` - WebP images (modern, efficient format)
     */
    icons: array(IconSchema).optional()
  });
  const BaseMetadataSchema = object({
    /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */
    name: string$1(),
    /**
     * Intended for UI and end-user contexts — optimized to be human-readable and easily understood,
     * even by those unfamiliar with domain-specific terminology.
     *
     * If not provided, the name should be used for display (except for Tool,
     * where `annotations.title` should be given precedence over using `name`,
     * if present).
     */
    title: string$1().optional()
  });
  const ImplementationSchema = BaseMetadataSchema.extend(__spreadProps(__spreadValues(__spreadValues({}, BaseMetadataSchema.shape), IconsSchema.shape), {
    version: string$1(),
    /**
     * An optional URL of the website for this implementation.
     */
    websiteUrl: string$1().optional(),
    /**
     * An optional human-readable description of what this implementation does.
     *
     * This can be used by clients or servers to provide context about their purpose
     * and capabilities. For example, a server might describe the types of resources
     * or tools it provides, while a client might describe its intended use case.
     */
    description: string$1().optional()
  }));
  const FormElicitationCapabilitySchema = intersection(object({
    applyDefaults: boolean$1().optional()
  }), record(string$1(), unknown()));
  const ElicitationCapabilitySchema = preprocess((value) => {
    if (value && typeof value === "object" && !Array.isArray(value)) {
      if (Object.keys(value).length === 0) {
        return { form: {} };
      }
    }
    return value;
  }, intersection(object({
    form: FormElicitationCapabilitySchema.optional(),
    url: AssertObjectSchema.optional()
  }), record(string$1(), unknown()).optional()));
  const ClientTasksCapabilitySchema = looseObject({
    /**
     * Present if the client supports listing tasks.
     */
    list: AssertObjectSchema.optional(),
    /**
     * Present if the client supports cancelling tasks.
     */
    cancel: AssertObjectSchema.optional(),
    /**
     * Capabilities for task creation on specific request types.
     */
    requests: looseObject({
      /**
       * Task support for sampling requests.
       */
      sampling: looseObject({
        createMessage: AssertObjectSchema.optional()
      }).optional(),
      /**
       * Task support for elicitation requests.
       */
      elicitation: looseObject({
        create: AssertObjectSchema.optional()
      }).optional()
    }).optional()
  });
  const ServerTasksCapabilitySchema = looseObject({
    /**
     * Present if the server supports listing tasks.
     */
    list: AssertObjectSchema.optional(),
    /**
     * Present if the server supports cancelling tasks.
     */
    cancel: AssertObjectSchema.optional(),
    /**
     * Capabilities for task creation on specific request types.
     */
    requests: looseObject({
      /**
       * Task support for tool requests.
       */
      tools: looseObject({
        call: AssertObjectSchema.optional()
      }).optional()
    }).optional()
  });
  const ClientCapabilitiesSchema = object({
    /**
     * Experimental, non-standard capabilities that the client supports.
     */
    experimental: record(string$1(), AssertObjectSchema).optional(),
    /**
     * Present if the client supports sampling from an LLM.
     */
    sampling: object({
      /**
       * Present if the client supports context inclusion via includeContext parameter.
       * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it).
       */
      context: AssertObjectSchema.optional(),
      /**
       * Present if the client supports tool use via tools and toolChoice parameters.
       */
      tools: AssertObjectSchema.optional()
    }).optional(),
    /**
     * Present if the client supports eliciting user input.
     */
    elicitation: ElicitationCapabilitySchema.optional(),
    /**
     * Present if the client supports listing roots.
     */
    roots: object({
      /**
       * Whether the client supports issuing notifications for changes to the roots list.
       */
      listChanged: boolean$1().optional()
    }).optional(),
    /**
     * Present if the client supports task creation.
     */
    tasks: ClientTasksCapabilitySchema.optional()
  });
  const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({
    /**
     * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well.
     */
    protocolVersion: string$1(),
    capabilities: ClientCapabilitiesSchema,
    clientInfo: ImplementationSchema
  });
  const InitializeRequestSchema = RequestSchema.extend({
    method: literal("initialize"),
    params: InitializeRequestParamsSchema
  });
  const ServerCapabilitiesSchema = object({
    /**
     * Experimental, non-standard capabilities that the server supports.
     */
    experimental: record(string$1(), AssertObjectSchema).optional(),
    /**
     * Present if the server supports sending log messages to the client.
     */
    logging: AssertObjectSchema.optional(),
    /**
     * Present if the server supports sending completions to the client.
     */
    completions: AssertObjectSchema.optional(),
    /**
     * Present if the server offers any prompt templates.
     */
    prompts: object({
      /**
       * Whether this server supports issuing notifications for changes to the prompt list.
       */
      listChanged: boolean$1().optional()
    }).optional(),
    /**
     * Present if the server offers any resources to read.
     */
    resources: object({
      /**
       * Whether this server supports clients subscribing to resource updates.
       */
      subscribe: boolean$1().optional(),
      /**
       * Whether this server supports issuing notifications for changes to the resource list.
       */
      listChanged: boolean$1().optional()
    }).optional(),
    /**
     * Present if the server offers any tools to call.
     */
    tools: object({
      /**
       * Whether this server supports issuing notifications for changes to the tool list.
       */
      listChanged: boolean$1().optional()
    }).optional(),
    /**
     * Present if the server supports task creation.
     */
    tasks: ServerTasksCapabilitySchema.optional()
  });
  const InitializeResultSchema = ResultSchema.extend({
    /**
     * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect.
     */
    protocolVersion: string$1(),
    capabilities: ServerCapabilitiesSchema,
    serverInfo: ImplementationSchema,
    /**
     * Instructions describing how to use the server and its features.
     *
     * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt.
     */
    instructions: string$1().optional()
  });
  const InitializedNotificationSchema = NotificationSchema.extend({
    method: literal("notifications/initialized"),
    params: NotificationsParamsSchema.optional()
  });
  const PingRequestSchema = RequestSchema.extend({
    method: literal("ping"),
    params: BaseRequestParamsSchema.optional()
  });
  const ProgressSchema = object({
    /**
     * The progress thus far. This should increase every time progress is made, even if the total is unknown.
     */
    progress: number$1(),
    /**
     * Total number of items to process (or total progress required), if known.
     */
    total: optional(number$1()),
    /**
     * An optional message describing the current progress.
     */
    message: optional(string$1())
  });
  const ProgressNotificationParamsSchema = object(__spreadProps(__spreadValues(__spreadValues({}, NotificationsParamsSchema.shape), ProgressSchema.shape), {
    /**
     * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding.
     */
    progressToken: ProgressTokenSchema
  }));
  const ProgressNotificationSchema = NotificationSchema.extend({
    method: literal("notifications/progress"),
    params: ProgressNotificationParamsSchema
  });
  const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({
    /**
     * An opaque token representing the current pagination position.
     * If provided, the server should return results starting after this cursor.
     */
    cursor: CursorSchema.optional()
  });
  const PaginatedRequestSchema = RequestSchema.extend({
    params: PaginatedRequestParamsSchema.optional()
  });
  const PaginatedResultSchema = ResultSchema.extend({
    /**
     * An opaque token representing the pagination position after the last returned result.
     * If present, there may be more results available.
     */
    nextCursor: CursorSchema.optional()
  });
  const TaskStatusSchema = _enum$1(["working", "input_required", "completed", "failed", "cancelled"]);
  const TaskSchema = object({
    taskId: string$1(),
    status: TaskStatusSchema,
    /**
     * Time in milliseconds to keep task results available after completion.
     * If null, the task has unlimited lifetime until manually cleaned up.
     */
    ttl: union([number$1(), _null()]),
    /**
     * ISO 8601 timestamp when the task was created.
     */
    createdAt: string$1(),
    /**
     * ISO 8601 timestamp when the task was last updated.
     */
    lastUpdatedAt: string$1(),
    pollInterval: optional(number$1()),
    /**
     * Optional diagnostic message for failed tasks or other status information.
     */
    statusMessage: optional(string$1())
  });
  const CreateTaskResultSchema = ResultSchema.extend({
    task: TaskSchema
  });
  const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema);
  const TaskStatusNotificationSchema = NotificationSchema.extend({
    method: literal("notifications/tasks/status"),
    params: TaskStatusNotificationParamsSchema
  });
  const GetTaskRequestSchema = RequestSchema.extend({
    method: literal("tasks/get"),
    params: BaseRequestParamsSchema.extend({
      taskId: string$1()
    })
  });
  const GetTaskResultSchema = ResultSchema.merge(TaskSchema);
  const GetTaskPayloadRequestSchema = RequestSchema.extend({
    method: literal("tasks/result"),
    params: BaseRequestParamsSchema.extend({
      taskId: string$1()
    })
  });
  ResultSchema.loose();
  const ListTasksRequestSchema = PaginatedRequestSchema.extend({
    method: literal("tasks/list")
  });
  const ListTasksResultSchema = PaginatedResultSchema.extend({
    tasks: array(TaskSchema)
  });
  const CancelTaskRequestSchema = RequestSchema.extend({
    method: literal("tasks/cancel"),
    params: BaseRequestParamsSchema.extend({
      taskId: string$1()
    })
  });
  const CancelTaskResultSchema = ResultSchema.merge(TaskSchema);
  const ResourceContentsSchema = object({
    /**
     * The URI of this resource.
     */
    uri: string$1(),
    /**
     * The MIME type of this resource, if known.
     */
    mimeType: optional(string$1()),
    /**
     * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
     * for notes on _meta usage.
     */
    _meta: record(string$1(), unknown()).optional()
  });
  const TextResourceContentsSchema = ResourceContentsSchema.extend({
    /**
     * The text of the item. This must only be set if the item can actually be represented as text (not binary data).
     */
    text: string$1()
  });
  const Base64Schema = string$1().refine((val) => {
    try {
      atob(val);
      return true;
    } catch (e) {
      return false;
    }
  }, { message: "Invalid Base64 string" });
  const BlobResourceContentsSchema = ResourceContentsSchema.extend({
    /**
     * A base64-encoded string representing the binary data of the item.
     */
    blob: Base64Schema
  });
  const RoleSchema = _enum$1(["user", "assistant"]);
  const AnnotationsSchema = object({
    /**
     * Intended audience(s) for the resource.
     */
    audience: array(RoleSchema).optional(),
    /**
     * Importance hint for the resource, from 0 (least) to 1 (most).
     */
    priority: number$1().min(0).max(1).optional(),
    /**
     * ISO 8601 timestamp for the most recent modification.
     */
    lastModified: datetime({ offset: true }).optional()
  });
  const ResourceSchema = object(__spreadProps(__spreadValues(__spreadValues({}, BaseMetadataSchema.shape), IconsSchema.shape), {
    /**
     * The URI of this resource.
     */
    uri: string$1(),
    /**
     * A description of what this resource represents.
     *
     * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model.
     */
    description: optional(string$1()),
    /**
     * The MIME type of this resource, if known.
     */
    mimeType: optional(string$1()),
    /**
     * Optional annotations for the client.
     */
    annotations: AnnotationsSchema.optional(),
    /**
     * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
     * for notes on _meta usage.
     */
    _meta: optional(looseObject({}))
  }));
  const ResourceTemplateSchema = object(__spreadProps(__spreadValues(__spreadValues({}, BaseMetadataSchema.shape), IconsSchema.shape), {
    /**
     * A URI template (according to RFC 6570) that can be used to construct resource URIs.
     */
    uriTemplate: string$1(),
    /**
     * A description of what this template is for.
     *
     * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model.
     */
    description: optional(string$1()),
    /**
     * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type.
     */
    mimeType: optional(string$1()),
    /**
     * Optional annotations for the client.
     */
    annotations: AnnotationsSchema.optional(),
    /**
     * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
     * for notes on _meta usage.
     */
    _meta: optional(looseObject({}))
  }));
  const ListResourcesRequestSchema = PaginatedRequestSchema.extend({
    method: literal("resources/list")
  });
  const ListResourcesResultSchema = PaginatedResultSchema.extend({
    resources: array(ResourceSchema)
  });
  const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({
    method: literal("resources/templates/list")
  });
  const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({
    resourceTemplates: array(ResourceTemplateSchema)
  });
  const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({
    /**
     * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.
     *
     * @format uri
     */
    uri: string$1()
  });
  const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema;
  const ReadResourceRequestSchema = RequestSchema.extend({
    method: literal("resources/read"),
    params: ReadResourceRequestParamsSchema
  });
  const ReadResourceResultSchema = ResultSchema.extend({
    contents: array(union([TextResourceContentsSchema, BlobResourceContentsSchema]))
  });
  const ResourceListChangedNotificationSchema = NotificationSchema.extend({
    method: literal("notifications/resources/list_changed"),
    params: NotificationsParamsSchema.optional()
  });
  const SubscribeRequestParamsSchema = ResourceRequestParamsSchema;
  const SubscribeRequestSchema = RequestSchema.extend({
    method: literal("resources/subscribe"),
    params: SubscribeRequestParamsSchema
  });
  const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema;
  const UnsubscribeRequestSchema = RequestSchema.extend({
    method: literal("resources/unsubscribe"),
    params: UnsubscribeRequestParamsSchema
  });
  const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({
    /**
     * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.
     */
    uri: string$1()
  });
  const ResourceUpdatedNotificationSchema = NotificationSchema.extend({
    method: literal("notifications/resources/updated"),
    params: ResourceUpdatedNotificationParamsSchema
  });
  const PromptArgumentSchema = object({
    /**
     * The name of the argument.
     */
    name: string$1(),
    /**
     * A human-readable description of the argument.
     */
    description: optional(string$1()),
    /**
     * Whether this argument must be provided.
     */
    required: optional(boolean$1())
  });
  const PromptSchema = object(__spreadProps(__spreadValues(__spreadValues({}, BaseMetadataSchema.shape), IconsSchema.shape), {
    /**
     * An optional description of what this prompt provides
     */
    description: optional(string$1()),
    /**
     * A list of arguments to use for templating the prompt.
     */
    arguments: optional(array(PromptArgumentSchema)),
    /**
     * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
     * for notes on _meta usage.
     */
    _meta: optional(looseObject({}))
  }));
  const ListPromptsRequestSchema = PaginatedRequestSchema.extend({
    method: literal("prompts/list")
  });
  const ListPromptsResultSchema = PaginatedResultSchema.extend({
    prompts: array(PromptSchema)
  });
  const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({
    /**
     * The name of the prompt or prompt template.
     */
    name: string$1(),
    /**
     * Arguments to use for templating the prompt.
     */
    arguments: record(string$1(), string$1()).optional()
  });
  const GetPromptRequestSchema = RequestSchema.extend({
    method: literal("prompts/get"),
    params: GetPromptRequestParamsSchema
  });
  const TextContentSchema = object({
    type: literal("text"),
    /**
     * The text content of the message.
     */
    text: string$1(),
    /**
     * Optional annotations for the client.
     */
    annotations: AnnotationsSchema.optional(),
    /**
     * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
     * for notes on _meta usage.
     */
    _meta: record(string$1(), unknown()).optional()
  });
  const ImageContentSchema = object({
    type: literal("image"),
    /**
     * The base64-encoded image data.
     */
    data: Base64Schema,
    /**
     * The MIME type of the image. Different providers may support different image types.
     */
    mimeType: string$1(),
    /**
     * Optional annotations for the client.
     */
    annotations: AnnotationsSchema.optional(),
    /**
     * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
     * for notes on _meta usage.
     */
    _meta: record(string$1(), unknown()).optional()
  });
  const AudioContentSchema = object({
    type: literal("audio"),
    /**
     * The base64-encoded audio data.
     */
    data: Base64Schema,
    /**
     * The MIME type of the audio. Different providers may support different audio types.
     */
    mimeType: string$1(),
    /**
     * Optional annotations for the client.
     */
    annotations: AnnotationsSchema.optional(),
    /**
     * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
     * for notes on _meta usage.
     */
    _meta: record(string$1(), unknown()).optional()
  });
  const ToolUseContentSchema = object({
    type: literal("tool_use"),
    /**
     * The name of the tool to invoke.
     * Must match a tool name from the request's tools array.
     */
    name: string$1(),
    /**
     * Unique identifier for this tool call.
     * Used to correlate with ToolResultContent in subsequent messages.
     */
    id: string$1(),
    /**
     * Arguments to pass to the tool.
     * Must conform to the tool's inputSchema.
     */
    input: record(string$1(), unknown()),
    /**
     * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
     * for notes on _meta usage.
     */
    _meta: record(string$1(), unknown()).optional()
  });
  const EmbeddedResourceSchema = object({
    type: literal("resource"),
    resource: union([TextResourceContentsSchema, BlobResourceContentsSchema]),
    /**
     * Optional annotations for the client.
     */
    annotations: AnnotationsSchema.optional(),
    /**
     * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
     * for notes on _meta usage.
     */
    _meta: record(string$1(), unknown()).optional()
  });
  const ResourceLinkSchema = ResourceSchema.extend({
    type: literal("resource_link")
  });
  const ContentBlockSchema = union([
    TextContentSchema,
    ImageContentSchema,
    AudioContentSchema,
    ResourceLinkSchema,
    EmbeddedResourceSchema
  ]);
  const PromptMessageSchema = object({
    role: RoleSchema,
    content: ContentBlockSchema
  });
  const GetPromptResultSchema = ResultSchema.extend({
    /**
     * An optional description for the prompt.
     */
    description: string$1().optional(),
    messages: array(PromptMessageSchema)
  });
  const PromptListChangedNotificationSchema = NotificationSchema.extend({
    method: literal("notifications/prompts/list_changed"),
    params: NotificationsParamsSchema.optional()
  });
  const ToolAnnotationsSchema = object({
    /**
     * A human-readable title for the tool.
     */
    title: string$1().optional(),
    /**
     * If true, the tool does not modify its environment.
     *
     * Default: false
     */
    readOnlyHint: boolean$1().optional(),
    /**
     * If true, the tool may perform destructive updates to its environment.
     * If false, the tool performs only additive updates.
     *
     * (This property is meaningful only when `readOnlyHint == false`)
     *
     * Default: true
     */
    destructiveHint: boolean$1().optional(),
    /**
     * If true, calling the tool repeatedly with the same arguments
     * will have no additional effect on the its environment.
     *
     * (This property is meaningful only when `readOnlyHint == false`)
     *
     * Default: false
     */
    idempotentHint: boolean$1().optional(),
    /**
     * If true, this tool may interact with an "open world" of external
     * entities. If false, the tool's domain of interaction is closed.
     * For example, the world of a web search tool is open, whereas that
     * of a memory tool is not.
     *
     * Default: true
     */
    openWorldHint: boolean$1().optional()
  });
  const ToolExecutionSchema = object({
    /**
     * Indicates the tool's preference for task-augmented execution.
     * - "required": Clients MUST invoke the tool as a task
     * - "optional": Clients MAY invoke the tool as a task or normal request
     * - "forbidden": Clients MUST NOT attempt to invoke the tool as a task
     *
     * If not present, defaults to "forbidden".
     */
    taskSupport: _enum$1(["required", "optional", "forbidden"]).optional()
  });
  const ToolSchema = object(__spreadProps(__spreadValues(__spreadValues({}, BaseMetadataSchema.shape), IconsSchema.shape), {
    /**
     * A human-readable description of the tool.
     */
    description: string$1().optional(),
    /**
     * A JSON Schema 2020-12 object defining the expected parameters for the tool.
     * Must have type: 'object' at the root level per MCP spec.
     */
    inputSchema: object({
      type: literal("object"),
      properties: record(string$1(), AssertObjectSchema).optional(),
      required: array(string$1()).optional()
    }).catchall(unknown()),
    /**
     * An optional JSON Schema 2020-12 object defining the structure of the tool's output
     * returned in the structuredContent field of a CallToolResult.
     * Must have type: 'object' at the root level per MCP spec.
     */
    outputSchema: object({
      type: literal("object"),
      properties: record(string$1(), AssertObjectSchema).optional(),
      required: array(string$1()).optional()
    }).catchall(unknown()).optional(),
    /**
     * Optional additional tool information.
     */
    annotations: ToolAnnotationsSchema.optional(),
    /**
     * Execution-related properties for this tool.
     */
    execution: ToolExecutionSchema.optional(),
    /**
     * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
     * for notes on _meta usage.
     */
    _meta: record(string$1(), unknown()).optional()
  }));
  const ListToolsRequestSchema = PaginatedRequestSchema.extend({
    method: literal("tools/list")
  });
  const ListToolsResultSchema = PaginatedResultSchema.extend({
    tools: array(ToolSchema)
  });
  const CallToolResultSchema = ResultSchema.extend({
    /**
     * A list of content objects that represent the result of the tool call.
     *
     * If the Tool does not define an outputSchema, this field MUST be present in the result.
     * For backwards compatibility, this field is always present, but it may be empty.
     */
    content: array(ContentBlockSchema).default([]),
    /**
     * An object containing structured tool output.
     *
     * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema.
     */
    structuredContent: record(string$1(), unknown()).optional(),
    /**
     * Whether the tool call ended in an error.
     *
     * If not set, this is assumed to be false (the call was successful).
     *
     * Any errors that originate from the tool SHOULD be reported inside the result
     * object, with `isError` set to true, _not_ as an MCP protocol-level error
     * response. Otherwise, the LLM would not be able to see that an error occurred
     * and self-correct.
     *
     * However, any errors in _finding_ the tool, an error indicating that the
     * server does not support tool calls, or any other exceptional conditions,
     * should be reported as an MCP error response.
     */
    isError: boolean$1().optional()
  });
  CallToolResultSchema.or(ResultSchema.extend({
    toolResult: unknown()
  }));
  const CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
    /**
     * The name of the tool to call.
     */
    name: string$1(),
    /**
     * Arguments to pass to the tool.
     */
    arguments: record(string$1(), unknown()).optional()
  });
  const CallToolRequestSchema = RequestSchema.extend({
    method: literal("tools/call"),
    params: CallToolRequestParamsSchema
  });
  const ToolListChangedNotificationSchema = NotificationSchema.extend({
    method: literal("notifications/tools/list_changed"),
    params: NotificationsParamsSchema.optional()
  });
  object({
    /**
     * If true, the list will be refreshed automatically when a list changed notification is received.
     * The callback will be called with the updated list.
     *
     * If false, the callback will be called with null items, allowing manual refresh.
     *
     * @default true
     */
    autoRefresh: boolean$1().default(true),
    /**
     * Debounce time in milliseconds for list changed notification processing.
     *
     * Multiple notifications received within this timeframe will only trigger one refresh.
     * Set to 0 to disable debouncing.
     *
     * @default 300
     */
    debounceMs: number$1().int().nonnegative().default(300)
  });
  const LoggingLevelSchema = _enum$1(["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"]);
  const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({
    /**
     * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message.
     */
    level: LoggingLevelSchema
  });
  const SetLevelRequestSchema = RequestSchema.extend({
    method: literal("logging/setLevel"),
    params: SetLevelRequestParamsSchema
  });
  const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({
    /**
     * The severity of this log message.
     */
    level: LoggingLevelSchema,
    /**
     * An optional name of the logger issuing this message.
     */
    logger: string$1().optional(),
    /**
     * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here.
     */
    data: unknown()
  });
  const LoggingMessageNotificationSchema = NotificationSchema.extend({
    method: literal("notifications/message"),
    params: LoggingMessageNotificationParamsSchema
  });
  const ModelHintSchema = object({
    /**
     * A hint for a model name.
     */
    name: string$1().optional()
  });
  const ModelPreferencesSchema = object({
    /**
     * Optional hints to use for model selection.
     */
    hints: array(ModelHintSchema).optional(),
    /**
     * How much to prioritize cost when selecting a model.
     */
    costPriority: number$1().min(0).max(1).optional(),
    /**
     * How much to prioritize sampling speed (latency) when selecting a model.
     */
    speedPriority: number$1().min(0).max(1).optional(),
    /**
     * How much to prioritize intelligence and capabilities when selecting a model.
     */
    intelligencePriority: number$1().min(0).max(1).optional()
  });
  const ToolChoiceSchema = object({
    /**
     * Controls when tools are used:
     * - "auto": Model decides whether to use tools (default)
     * - "required": Model MUST use at least one tool before completing
     * - "none": Model MUST NOT use any tools
     */
    mode: _enum$1(["auto", "required", "none"]).optional()
  });
  const ToolResultContentSchema = object({
    type: literal("tool_result"),
    toolUseId: string$1().describe("The unique identifier for the corresponding tool call."),
    content: array(ContentBlockSchema).default([]),
    structuredContent: object({}).loose().optional(),
    isError: boolean$1().optional(),
    /**
     * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
     * for notes on _meta usage.
     */
    _meta: record(string$1(), unknown()).optional()
  });
  const SamplingContentSchema = discriminatedUnion("type", [TextContentSchema, ImageContentSchema, AudioContentSchema]);
  const SamplingMessageContentBlockSchema = discriminatedUnion("type", [
    TextContentSchema,
    ImageContentSchema,
    AudioContentSchema,
    ToolUseContentSchema,
    ToolResultContentSchema
  ]);
  const SamplingMessageSchema = object({
    role: RoleSchema,
    content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]),
    /**
     * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
     * for notes on _meta usage.
     */
    _meta: record(string$1(), unknown()).optional()
  });
  const CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
    messages: array(SamplingMessageSchema),
    /**
     * The server's preferences for which model to select. The client MAY modify or omit this request.
     */
    modelPreferences: ModelPreferencesSchema.optional(),
    /**
     * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.
     */
    systemPrompt: string$1().optional(),
    /**
     * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt.
     * The client MAY ignore this request.
     *
     * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client
     * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases.
     */
    includeContext: _enum$1(["none", "thisServer", "allServers"]).optional(),
    temperature: number$1().optional(),
    /**
     * The requested maximum number of tokens to sample (to prevent runaway completions).
     *
     * The client MAY choose to sample fewer tokens than the requested maximum.
     */
    maxTokens: number$1().int(),
    stopSequences: array(string$1()).optional(),
    /**
     * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.
     */
    metadata: AssertObjectSchema.optional(),
    /**
     * Tools that the model may use during generation.
     * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.
     */
    tools: array(ToolSchema).optional(),
    /**
     * Controls how the model uses tools.
     * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.
     * Default is `{ mode: "auto" }`.
     */
    toolChoice: ToolChoiceSchema.optional()
  });
  const CreateMessageRequestSchema = RequestSchema.extend({
    method: literal("sampling/createMessage"),
    params: CreateMessageRequestParamsSchema
  });
  const CreateMessageResultSchema = ResultSchema.extend({
    /**
     * The name of the model that generated the message.
     */
    model: string$1(),
    /**
     * The reason why sampling stopped, if known.
     *
     * Standard values:
     * - "endTurn": Natural end of the assistant's turn
     * - "stopSequence": A stop sequence was encountered
     * - "maxTokens": Maximum token limit was reached
     *
     * This field is an open string to allow for provider-specific stop reasons.
     */
    stopReason: optional(_enum$1(["endTurn", "stopSequence", "maxTokens"]).or(string$1())),
    role: RoleSchema,
    /**
     * Response content. Single content block (text, image, or audio).
     */
    content: SamplingContentSchema
  });
  const CreateMessageResultWithToolsSchema = ResultSchema.extend({
    /**
     * The name of the model that generated the message.
     */
    model: string$1(),
    /**
     * The reason why sampling stopped, if known.
     *
     * Standard values:
     * - "endTurn": Natural end of the assistant's turn
     * - "stopSequence": A stop sequence was encountered
     * - "maxTokens": Maximum token limit was reached
     * - "toolUse": The model wants to use one or more tools
     *
     * This field is an open string to allow for provider-specific stop reasons.
     */
    stopReason: optional(_enum$1(["endTurn", "stopSequence", "maxTokens", "toolUse"]).or(string$1())),
    role: RoleSchema,
    /**
     * Response content. May be a single block or array. May include ToolUseContent if stopReason is "toolUse".
     */
    content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)])
  });
  const BooleanSchemaSchema = object({
    type: literal("boolean"),
    title: string$1().optional(),
    description: string$1().optional(),
    default: boolean$1().optional()
  });
  const StringSchemaSchema = object({
    type: literal("string"),
    title: string$1().optional(),
    description: string$1().optional(),
    minLength: number$1().optional(),
    maxLength: number$1().optional(),
    format: _enum$1(["email", "uri", "date", "date-time"]).optional(),
    default: string$1().optional()
  });
  const NumberSchemaSchema = object({
    type: _enum$1(["number", "integer"]),
    title: string$1().optional(),
    description: string$1().optional(),
    minimum: number$1().optional(),
    maximum: number$1().optional(),
    default: number$1().optional()
  });
  const UntitledSingleSelectEnumSchemaSchema = object({
    type: literal("string"),
    title: string$1().optional(),
    description: string$1().optional(),
    enum: array(string$1()),
    default: string$1().optional()
  });
  const TitledSingleSelectEnumSchemaSchema = object({
    type: literal("string"),
    title: string$1().optional(),
    description: string$1().optional(),
    oneOf: array(object({
      const: string$1(),
      title: string$1()
    })),
    default: string$1().optional()
  });
  const LegacyTitledEnumSchemaSchema = object({
    type: literal("string"),
    title: string$1().optional(),
    description: string$1().optional(),
    enum: array(string$1()),
    enumNames: array(string$1()).optional(),
    default: string$1().optional()
  });
  const SingleSelectEnumSchemaSchema = union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);
  const UntitledMultiSelectEnumSchemaSchema = object({
    type: literal("array"),
    title: string$1().optional(),
    description: string$1().optional(),
    minItems: number$1().optional(),
    maxItems: number$1().optional(),
    items: object({
      type: literal("string"),
      enum: array(string$1())
    }),
    default: array(string$1()).optional()
  });
  const TitledMultiSelectEnumSchemaSchema = object({
    type: literal("array"),
    title: string$1().optional(),
    description: string$1().optional(),
    minItems: number$1().optional(),
    maxItems: number$1().optional(),
    items: object({
      anyOf: array(object({
        const: string$1(),
        title: string$1()
      }))
    }),
    default: array(string$1()).optional()
  });
  const MultiSelectEnumSchemaSchema = union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);
  const EnumSchemaSchema = union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);
  const PrimitiveSchemaDefinitionSchema = union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);
  const ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({
    /**
     * The elicitation mode.
     *
     * Optional for backward compatibility. Clients MUST treat missing mode as "form".
     */
    mode: literal("form").optional(),
    /**
     * The message to present to the user describing what information is being requested.
     */
    message: string$1(),
    /**
     * A restricted subset of JSON Schema.
     * Only top-level properties are allowed, without nesting.
     */
    requestedSchema: object({
      type: literal("object"),
      properties: record(string$1(), PrimitiveSchemaDefinitionSchema),
      required: array(string$1()).optional()
    })
  });
  const ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({
    /**
     * The elicitation mode.
     */
    mode: literal("url"),
    /**
     * The message to present to the user explaining why the interaction is needed.
     */
    message: string$1(),
    /**
     * The ID of the elicitation, which must be unique within the context of the server.
     * The client MUST treat this ID as an opaque value.
     */
    elicitationId: string$1(),
    /**
     * The URL that the user should navigate to.
     */
    url: string$1().url()
  });
  const ElicitRequestParamsSchema = union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]);
  const ElicitRequestSchema = RequestSchema.extend({
    method: literal("elicitation/create"),
    params: ElicitRequestParamsSchema
  });
  const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({
    /**
     * The ID of the elicitation that completed.
     */
    elicitationId: string$1()
  });
  const ElicitationCompleteNotificationSchema = NotificationSchema.extend({
    method: literal("notifications/elicitation/complete"),
    params: ElicitationCompleteNotificationParamsSchema
  });
  const ElicitResultSchema = ResultSchema.extend({
    /**
     * The user action in response to the elicitation.
     * - "accept": User submitted the form/confirmed the action
     * - "decline": User explicitly decline the action
     * - "cancel": User dismissed without making an explicit choice
     */
    action: _enum$1(["accept", "decline", "cancel"]),
    /**
     * The submitted form data, only present when action is "accept".
     * Contains values matching the requested schema.
     * Per MCP spec, content is "typically omitted" for decline/cancel actions.
     * We normalize null to undefined for leniency while maintaining type compatibility.
     */
    content: preprocess((val) => val === null ? void 0 : val, record(string$1(), union([string$1(), number$1(), boolean$1(), array(string$1())])).optional())
  });
  const ResourceTemplateReferenceSchema = object({
    type: literal("ref/resource"),
    /**
     * The URI or URI template of the resource.
     */
    uri: string$1()
  });
  const PromptReferenceSchema = object({
    type: literal("ref/prompt"),
    /**
     * The name of the prompt or prompt template
     */
    name: string$1()
  });
  const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({
    ref: union([PromptReferenceSchema, ResourceTemplateReferenceSchema]),
    /**
     * The argument's information
     */
    argument: object({
      /**
       * The name of the argument
       */
      name: string$1(),
      /**
       * The value of the argument to use for completion matching.
       */
      value: string$1()
    }),
    context: object({
      /**
       * Previously-resolved variables in a URI template or prompt.
       */
      arguments: record(string$1(), string$1()).optional()
    }).optional()
  });
  const CompleteRequestSchema = RequestSchema.extend({
    method: literal("completion/complete"),
    params: CompleteRequestParamsSchema
  });
  const CompleteResultSchema = ResultSchema.extend({
    completion: looseObject({
      /**
       * An array of completion values. Must not exceed 100 items.
       */
      values: array(string$1()).max(100),
      /**
       * The total number of completion options available. This can exceed the number of values actually sent in the response.
       */
      total: optional(number$1().int()),
      /**
       * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.
       */
      hasMore: optional(boolean$1())
    })
  });
  const RootSchema = object({
    /**
     * The URI identifying the root. This *must* start with file:// for now.
     */
    uri: string$1().startsWith("file://"),
    /**
     * An optional name for the root.
     */
    name: string$1().optional(),
    /**
     * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
     * for notes on _meta usage.
     */
    _meta: record(string$1(), unknown()).optional()
  });
  const ListRootsRequestSchema = RequestSchema.extend({
    method: literal("roots/list"),
    params: BaseRequestParamsSchema.optional()
  });
  const ListRootsResultSchema = ResultSchema.extend({
    roots: array(RootSchema)
  });
  const RootsListChangedNotificationSchema = NotificationSchema.extend({
    method: literal("notifications/roots/list_changed"),
    params: NotificationsParamsSchema.optional()
  });
  union([
    PingRequestSchema,
    InitializeRequestSchema,
    CompleteRequestSchema,
    SetLevelRequestSchema,
    GetPromptRequestSchema,
    ListPromptsRequestSchema,
    ListResourcesRequestSchema,
    ListResourceTemplatesRequestSchema,
    ReadResourceRequestSchema,
    SubscribeRequestSchema,
    UnsubscribeRequestSchema,
    CallToolRequestSchema,
    ListToolsRequestSchema,
    GetTaskRequestSchema,
    GetTaskPayloadRequestSchema,
    ListTasksRequestSchema,
    CancelTaskRequestSchema
  ]);
  union([
    CancelledNotificationSchema,
    ProgressNotificationSchema,
    InitializedNotificationSchema,
    RootsListChangedNotificationSchema,
    TaskStatusNotificationSchema
  ]);
  union([
    EmptyResultSchema,
    CreateMessageResultSchema,
    CreateMessageResultWithToolsSchema,
    ElicitResultSchema,
    ListRootsResultSchema,
    GetTaskResultSchema,
    ListTasksResultSchema,
    CreateTaskResultSchema
  ]);
  union([
    PingRequestSchema,
    CreateMessageRequestSchema,
    ElicitRequestSchema,
    ListRootsRequestSchema,
    GetTaskRequestSchema,
    GetTaskPayloadRequestSchema,
    ListTasksRequestSchema,
    CancelTaskRequestSchema
  ]);
  union([
    CancelledNotificationSchema,
    ProgressNotificationSchema,
    LoggingMessageNotificationSchema,
    ResourceUpdatedNotificationSchema,
    ResourceListChangedNotificationSchema,
    ToolListChangedNotificationSchema,
    PromptListChangedNotificationSchema,
    TaskStatusNotificationSchema,
    ElicitationCompleteNotificationSchema
  ]);
  union([
    EmptyResultSchema,
    InitializeResultSchema,
    CompleteResultSchema,
    GetPromptResultSchema,
    ListPromptsResultSchema,
    ListResourcesResultSchema,
    ListResourceTemplatesResultSchema,
    ReadResourceResultSchema,
    CallToolResultSchema,
    ListToolsResultSchema,
    GetTaskResultSchema,
    ListTasksResultSchema,
    CreateTaskResultSchema
  ]);
  class McpError extends Error {
    constructor(code2, message, data) {
      super(`MCP error ${code2}: ${message}`);
      this.code = code2;
      this.data = data;
      this.name = "McpError";
    }
    /**
     * Factory method to create the appropriate error type based on the error code and data
     */
    static fromError(code2, message, data) {
      if (code2 === ErrorCode.UrlElicitationRequired && data) {
        const errorData = data;
        if (errorData.elicitations) {
          return new UrlElicitationRequiredError(errorData.elicitations, message);
        }
      }
      return new McpError(code2, message, data);
    }
  }
  class UrlElicitationRequiredError extends McpError {
    constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) {
      super(ErrorCode.UrlElicitationRequired, message, {
        elicitations
      });
    }
    get elicitations() {
      var _a3, _b2;
      return (_b2 = (_a3 = this.data) == null ? void 0 : _a3.elicitations) != null ? _b2 : [];
    }
  }
  function isTerminal(status) {
    return status === "completed" || status === "failed" || status === "cancelled";
  }
  new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
  function getMethodLiteral(schema) {
    const shape = getObjectShape(schema);
    const methodSchema = shape == null ? void 0 : shape.method;
    if (!methodSchema) {
      throw new Error("Schema is missing a method literal");
    }
    const value = getLiteralValue(methodSchema);
    if (typeof value !== "string") {
      throw new Error("Schema method literal must be a string");
    }
    return value;
  }
  function parseWithCompat(schema, data) {
    const result2 = safeParse$1(schema, data);
    if (!result2.success) {
      throw result2.error;
    }
    return result2.data;
  }
  const DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4;
  class Protocol {
    constructor(_options) {
      this._options = _options;
      this._requestMessageId = 0;
      this._requestHandlers = /* @__PURE__ */ new Map();
      this._requestHandlerAbortControllers = /* @__PURE__ */ new Map();
      this._notificationHandlers = /* @__PURE__ */ new Map();
      this._responseHandlers = /* @__PURE__ */ new Map();
      this._progressHandlers = /* @__PURE__ */ new Map();
      this._timeoutInfo = /* @__PURE__ */ new Map();
      this._pendingDebouncedNotifications = /* @__PURE__ */ new Set();
      this._taskProgressTokens = /* @__PURE__ */ new Map();
      this._requestResolvers = /* @__PURE__ */ new Map();
      this.setNotificationHandler(CancelledNotificationSchema, (notification) => {
        this._oncancel(notification);
      });
      this.setNotificationHandler(ProgressNotificationSchema, (notification) => {
        this._onprogress(notification);
      });
      this.setRequestHandler(
        PingRequestSchema,
        // Automatic pong by default.
        (_request) => ({})
      );
      this._taskStore = _options == null ? void 0 : _options.taskStore;
      this._taskMessageQueue = _options == null ? void 0 : _options.taskMessageQueue;
      if (this._taskStore) {
        this.setRequestHandler(GetTaskRequestSchema, (request, extra) => __async(this, null, function* () {
          const task = yield this._taskStore.getTask(request.params.taskId, extra.sessionId);
          if (!task) {
            throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found");
          }
          return __spreadValues({}, task);
        }));
        this.setRequestHandler(GetTaskPayloadRequestSchema, (request, extra) => __async(this, null, function* () {
          const handleTaskResult = () => __async(this, null, function* () {
            var _a3;
            const taskId = request.params.taskId;
            if (this._taskMessageQueue) {
              let queuedMessage;
              while (queuedMessage = yield this._taskMessageQueue.dequeue(taskId, extra.sessionId)) {
                if (queuedMessage.type === "response" || queuedMessage.type === "error") {
                  const message = queuedMessage.message;
                  const requestId = message.id;
                  const resolver = this._requestResolvers.get(requestId);
                  if (resolver) {
                    this._requestResolvers.delete(requestId);
                    if (queuedMessage.type === "response") {
                      resolver(message);
                    } else {
                      const errorMessage = message;
                      const error2 = new McpError(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data);
                      resolver(error2);
                    }
                  } else {
                    const messageType = queuedMessage.type === "response" ? "Response" : "Error";
                    this._onerror(new Error(`${messageType} handler missing for request ${requestId}`));
                  }
                  continue;
                }
                yield (_a3 = this._transport) == null ? void 0 : _a3.send(queuedMessage.message, { relatedRequestId: extra.requestId });
              }
            }
            const task = yield this._taskStore.getTask(taskId, extra.sessionId);
            if (!task) {
              throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);
            }
            if (!isTerminal(task.status)) {
              yield this._waitForTaskUpdate(taskId, extra.signal);
              return yield handleTaskResult();
            }
            if (isTerminal(task.status)) {
              const result2 = yield this._taskStore.getTaskResult(taskId, extra.sessionId);
              this._clearTaskQueue(taskId);
              return __spreadProps(__spreadValues({}, result2), {
                _meta: __spreadProps(__spreadValues({}, result2._meta), {
                  [RELATED_TASK_META_KEY]: {
                    taskId
                  }
                })
              });
            }
            return yield handleTaskResult();
          });
          return yield handleTaskResult();
        }));
        this.setRequestHandler(ListTasksRequestSchema, (request, extra) => __async(this, null, function* () {
          var _a3;
          try {
            const { tasks, nextCursor } = yield this._taskStore.listTasks((_a3 = request.params) == null ? void 0 : _a3.cursor, extra.sessionId);
            return {
              tasks,
              nextCursor,
              _meta: {}
            };
          } catch (error2) {
            throw new McpError(ErrorCode.InvalidParams, `Failed to list tasks: ${error2 instanceof Error ? error2.message : String(error2)}`);
          }
        }));
        this.setRequestHandler(CancelTaskRequestSchema, (request, extra) => __async(this, null, function* () {
          try {
            const task = yield this._taskStore.getTask(request.params.taskId, extra.sessionId);
            if (!task) {
              throw new McpError(ErrorCode.InvalidParams, `Task not found: ${request.params.taskId}`);
            }
            if (isTerminal(task.status)) {
              throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`);
            }
            yield this._taskStore.updateTaskStatus(request.params.taskId, "cancelled", "Client cancelled task execution.", extra.sessionId);
            this._clearTaskQueue(request.params.taskId);
            const cancelledTask = yield this._taskStore.getTask(request.params.taskId, extra.sessionId);
            if (!cancelledTask) {
              throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`);
            }
            return __spreadValues({
              _meta: {}
            }, cancelledTask);
          } catch (error2) {
            if (error2 instanceof McpError) {
              throw error2;
            }
            throw new McpError(ErrorCode.InvalidRequest, `Failed to cancel task: ${error2 instanceof Error ? error2.message : String(error2)}`);
          }
        }));
      }
    }
    _oncancel(notification) {
      return __async(this, null, function* () {
        if (!notification.params.requestId) {
          return;
        }
        const controller = this._requestHandlerAbortControllers.get(notification.params.requestId);
        controller == null ? void 0 : controller.abort(notification.params.reason);
      });
    }
    _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) {
      this._timeoutInfo.set(messageId, {
        timeoutId: setTimeout(onTimeout, timeout),
        startTime: Date.now(),
        timeout,
        maxTotalTimeout,
        resetTimeoutOnProgress,
        onTimeout
      });
    }
    _resetTimeout(messageId) {
      const info = this._timeoutInfo.get(messageId);
      if (!info)
        return false;
      const totalElapsed = Date.now() - info.startTime;
      if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) {
        this._timeoutInfo.delete(messageId);
        throw McpError.fromError(ErrorCode.RequestTimeout, "Maximum total timeout exceeded", {
          maxTotalTimeout: info.maxTotalTimeout,
          totalElapsed
        });
      }
      clearTimeout(info.timeoutId);
      info.timeoutId = setTimeout(info.onTimeout, info.timeout);
      return true;
    }
    _cleanupTimeout(messageId) {
      const info = this._timeoutInfo.get(messageId);
      if (info) {
        clearTimeout(info.timeoutId);
        this._timeoutInfo.delete(messageId);
      }
    }
    /**
     * Attaches to the given transport, starts it, and starts listening for messages.
     *
     * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward.
     */
    connect(transport) {
      return __async(this, null, function* () {
        var _a3, _b2, _c2;
        this._transport = transport;
        const _onclose = (_a3 = this.transport) == null ? void 0 : _a3.onclose;
        this._transport.onclose = () => {
          _onclose == null ? void 0 : _onclose();
          this._onclose();
        };
        const _onerror = (_b2 = this.transport) == null ? void 0 : _b2.onerror;
        this._transport.onerror = (error2) => {
          _onerror == null ? void 0 : _onerror(error2);
          this._onerror(error2);
        };
        const _onmessage = (_c2 = this._transport) == null ? void 0 : _c2.onmessage;
        this._transport.onmessage = (message, extra) => {
          _onmessage == null ? void 0 : _onmessage(message, extra);
          if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {
            this._onresponse(message);
          } else if (isJSONRPCRequest(message)) {
            this._onrequest(message, extra);
          } else if (isJSONRPCNotification(message)) {
            this._onnotification(message);
          } else {
            this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`));
          }
        };
        yield this._transport.start();
      });
    }
    _onclose() {
      var _a3;
      const responseHandlers = this._responseHandlers;
      this._responseHandlers = /* @__PURE__ */ new Map();
      this._progressHandlers.clear();
      this._taskProgressTokens.clear();
      this._pendingDebouncedNotifications.clear();
      const error2 = McpError.fromError(ErrorCode.ConnectionClosed, "Connection closed");
      this._transport = void 0;
      (_a3 = this.onclose) == null ? void 0 : _a3.call(this);
      for (const handler of responseHandlers.values()) {
        handler(error2);
      }
    }
    _onerror(error2) {
      var _a3;
      (_a3 = this.onerror) == null ? void 0 : _a3.call(this, error2);
    }
    _onnotification(notification) {
      var _a3;
      const handler = (_a3 = this._notificationHandlers.get(notification.method)) != null ? _a3 : this.fallbackNotificationHandler;
      if (handler === void 0) {
        return;
      }
      Promise.resolve().then(() => handler(notification)).catch((error2) => this._onerror(new Error(`Uncaught error in notification handler: ${error2}`)));
    }
    _onrequest(request, extra) {
      var _a3, _b2, _c2, _d2, _e;
      const handler = (_a3 = this._requestHandlers.get(request.method)) != null ? _a3 : this.fallbackRequestHandler;
      const capturedTransport = this._transport;
      const relatedTaskId = (_d2 = (_c2 = (_b2 = request.params) == null ? void 0 : _b2._meta) == null ? void 0 : _c2[RELATED_TASK_META_KEY]) == null ? void 0 : _d2.taskId;
      if (handler === void 0) {
        const errorResponse = {
          jsonrpc: "2.0",
          id: request.id,
          error: {
            code: ErrorCode.MethodNotFound,
            message: "Method not found"
          }
        };
        if (relatedTaskId && this._taskMessageQueue) {
          this._enqueueTaskMessage(relatedTaskId, {
            type: "error",
            message: errorResponse,
            timestamp: Date.now()
          }, capturedTransport == null ? void 0 : capturedTransport.sessionId).catch((error2) => this._onerror(new Error(`Failed to enqueue error response: ${error2}`)));
        } else {
          capturedTransport == null ? void 0 : capturedTransport.send(errorResponse).catch((error2) => this._onerror(new Error(`Failed to send an error response: ${error2}`)));
        }
        return;
      }
      const abortController = new AbortController();
      this._requestHandlerAbortControllers.set(request.id, abortController);
      const taskCreationParams = isTaskAugmentedRequestParams(request.params) ? request.params.task : void 0;
      const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport == null ? void 0 : capturedTransport.sessionId) : void 0;
      const fullExtra = {
        signal: abortController.signal,
        sessionId: capturedTransport == null ? void 0 : capturedTransport.sessionId,
        _meta: (_e = request.params) == null ? void 0 : _e._meta,
        sendNotification: (notification) => __async(this, null, function* () {
          const notificationOptions = { relatedRequestId: request.id };
          if (relatedTaskId) {
            notificationOptions.relatedTask = { taskId: relatedTaskId };
          }
          yield this.notification(notification, notificationOptions);
        }),
        sendRequest: (r, resultSchema, options) => __async(this, null, function* () {
          var _a4, _b3;
          const requestOptions = __spreadProps(__spreadValues({}, options), { relatedRequestId: request.id });
          if (relatedTaskId && !requestOptions.relatedTask) {
            requestOptions.relatedTask = { taskId: relatedTaskId };
          }
          const effectiveTaskId = (_b3 = (_a4 = requestOptions.relatedTask) == null ? void 0 : _a4.taskId) != null ? _b3 : relatedTaskId;
          if (effectiveTaskId && taskStore) {
            yield taskStore.updateTaskStatus(effectiveTaskId, "input_required");
          }
          return yield this.request(r, resultSchema, requestOptions);
        }),
        authInfo: extra == null ? void 0 : extra.authInfo,
        requestId: request.id,
        requestInfo: extra == null ? void 0 : extra.requestInfo,
        taskId: relatedTaskId,
        taskStore,
        taskRequestedTtl: taskCreationParams == null ? void 0 : taskCreationParams.ttl,
        closeSSEStream: extra == null ? void 0 : extra.closeSSEStream,
        closeStandaloneSSEStream: extra == null ? void 0 : extra.closeStandaloneSSEStream
      };
      Promise.resolve().then(() => {
        if (taskCreationParams) {
          this.assertTaskHandlerCapability(request.method);
        }
      }).then(() => handler(request, fullExtra)).then((result2) => __async(this, null, function* () {
        if (abortController.signal.aborted) {
          return;
        }
        const response = {
          result: result2,
          jsonrpc: "2.0",
          id: request.id
        };
        if (relatedTaskId && this._taskMessageQueue) {
          yield this._enqueueTaskMessage(relatedTaskId, {
            type: "response",
            message: response,
            timestamp: Date.now()
          }, capturedTransport == null ? void 0 : capturedTransport.sessionId);
        } else {
          yield capturedTransport == null ? void 0 : capturedTransport.send(response);
        }
      }), (error2) => __async(this, null, function* () {
        var _a4;
        if (abortController.signal.aborted) {
          return;
        }
        const errorResponse = {
          jsonrpc: "2.0",
          id: request.id,
          error: __spreadValues({
            code: Number.isSafeInteger(error2["code"]) ? error2["code"] : ErrorCode.InternalError,
            message: (_a4 = error2.message) != null ? _a4 : "Internal error"
          }, error2["data"] !== void 0 && { data: error2["data"] })
        };
        if (relatedTaskId && this._taskMessageQueue) {
          yield this._enqueueTaskMessage(relatedTaskId, {
            type: "error",
            message: errorResponse,
            timestamp: Date.now()
          }, capturedTransport == null ? void 0 : capturedTransport.sessionId);
        } else {
          yield capturedTransport == null ? void 0 : capturedTransport.send(errorResponse);
        }
      })).catch((error2) => this._onerror(new Error(`Failed to send response: ${error2}`))).finally(() => {
        this._requestHandlerAbortControllers.delete(request.id);
      });
    }
    _onprogress(notification) {
      const _a3 = notification.params, { progressToken } = _a3, params = __objRest(_a3, ["progressToken"]);
      const messageId = Number(progressToken);
      const handler = this._progressHandlers.get(messageId);
      if (!handler) {
        this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));
        return;
      }
      const responseHandler = this._responseHandlers.get(messageId);
      const timeoutInfo = this._timeoutInfo.get(messageId);
      if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) {
        try {
          this._resetTimeout(messageId);
        } catch (error2) {
          this._responseHandlers.delete(messageId);
          this._progressHandlers.delete(messageId);
          this._cleanupTimeout(messageId);
          responseHandler(error2);
          return;
        }
      }
      handler(params);
    }
    _onresponse(response) {
      const messageId = Number(response.id);
      const resolver = this._requestResolvers.get(messageId);
      if (resolver) {
        this._requestResolvers.delete(messageId);
        if (isJSONRPCResultResponse(response)) {
          resolver(response);
        } else {
          const error2 = new McpError(response.error.code, response.error.message, response.error.data);
          resolver(error2);
        }
        return;
      }
      const handler = this._responseHandlers.get(messageId);
      if (handler === void 0) {
        this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));
        return;
      }
      this._responseHandlers.delete(messageId);
      this._cleanupTimeout(messageId);
      let isTaskResponse = false;
      if (isJSONRPCResultResponse(response) && response.result && typeof response.result === "object") {
        const result2 = response.result;
        if (result2.task && typeof result2.task === "object") {
          const task = result2.task;
          if (typeof task.taskId === "string") {
            isTaskResponse = true;
            this._taskProgressTokens.set(task.taskId, messageId);
          }
        }
      }
      if (!isTaskResponse) {
        this._progressHandlers.delete(messageId);
      }
      if (isJSONRPCResultResponse(response)) {
        handler(response);
      } else {
        const error2 = McpError.fromError(response.error.code, response.error.message, response.error.data);
        handler(error2);
      }
    }
    get transport() {
      return this._transport;
    }
    /**
     * Closes the connection.
     */
    close() {
      return __async(this, null, function* () {
        var _a3;
        yield (_a3 = this._transport) == null ? void 0 : _a3.close();
      });
    }
    /**
     * Sends a request and returns an AsyncGenerator that yields response messages.
     * The generator is guaranteed to end with either a 'result' or 'error' message.
     *
     * @example
     * ```typescript
     * const stream = protocol.requestStream(request, resultSchema, options);
     * for await (const message of stream) {
     *   switch (message.type) {
     *     case 'taskCreated':
     *       console.log('Task created:', message.task.taskId);
     *       break;
     *     case 'taskStatus':
     *       console.log('Task status:', message.task.status);
     *       break;
     *     case 'result':
     *       console.log('Final result:', message.result);
     *       break;
     *     case 'error':
     *       console.error('Error:', message.error);
     *       break;
     *   }
     * }
     * ```
     *
     * @experimental Use `client.experimental.tasks.requestStream()` to access this method.
     */
    requestStream(request, resultSchema, options) {
      return __asyncGenerator(this, null, function* () {
        var _a3, _b2, _c2, _d2;
        const { task } = options != null ? options : {};
        if (!task) {
          try {
            const result2 = yield new __await(this.request(request, resultSchema, options));
            yield { type: "result", result: result2 };
          } catch (error2) {
            yield {
              type: "error",
              error: error2 instanceof McpError ? error2 : new McpError(ErrorCode.InternalError, String(error2))
            };
          }
          return;
        }
        let taskId;
        try {
          const createResult = yield new __await(this.request(request, CreateTaskResultSchema, options));
          if (createResult.task) {
            taskId = createResult.task.taskId;
            yield { type: "taskCreated", task: createResult.task };
          } else {
            throw new McpError(ErrorCode.InternalError, "Task creation did not return a task");
          }
          while (true) {
            const task2 = yield new __await(this.getTask({ taskId }, options));
            yield { type: "taskStatus", task: task2 };
            if (isTerminal(task2.status)) {
              if (task2.status === "completed") {
                const result2 = yield new __await(this.getTaskResult({ taskId }, resultSchema, options));
                yield { type: "result", result: result2 };
              } else if (task2.status === "failed") {
                yield {
                  type: "error",
                  error: new McpError(ErrorCode.InternalError, `Task ${taskId} failed`)
                };
              } else if (task2.status === "cancelled") {
                yield {
                  type: "error",
                  error: new McpError(ErrorCode.InternalError, `Task ${taskId} was cancelled`)
                };
              }
              return;
            }
            if (task2.status === "input_required") {
              const result2 = yield new __await(this.getTaskResult({ taskId }, resultSchema, options));
              yield { type: "result", result: result2 };
              return;
            }
            const pollInterval = (_c2 = (_b2 = task2.pollInterval) != null ? _b2 : (_a3 = this._options) == null ? void 0 : _a3.defaultTaskPollInterval) != null ? _c2 : 1e3;
            yield new __await(new Promise((resolve2) => setTimeout(resolve2, pollInterval)));
            (_d2 = options == null ? void 0 : options.signal) == null ? void 0 : _d2.throwIfAborted();
          }
        } catch (error2) {
          yield {
            type: "error",
            error: error2 instanceof McpError ? error2 : new McpError(ErrorCode.InternalError, String(error2))
          };
        }
      });
    }
    /**
     * Sends a request and waits for a response.
     *
     * Do not use this method to emit notifications! Use notification() instead.
     */
    request(request, resultSchema, options) {
      const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options != null ? options : {};
      return new Promise((resolve2, reject) => {
        var _a3, _b2, _c2, _d2, _e, _f, _g;
        const earlyReject = (error2) => {
          reject(error2);
        };
        if (!this._transport) {
          earlyReject(new Error("Not connected"));
          return;
        }
        if (((_a3 = this._options) == null ? void 0 : _a3.enforceStrictCapabilities) === true) {
          try {
            this.assertCapabilityForMethod(request.method);
            if (task) {
              this.assertTaskCapability(request.method);
            }
          } catch (e) {
            earlyReject(e);
            return;
          }
        }
        (_b2 = options == null ? void 0 : options.signal) == null ? void 0 : _b2.throwIfAborted();
        const messageId = this._requestMessageId++;
        const jsonrpcRequest = __spreadProps(__spreadValues({}, request), {
          jsonrpc: "2.0",
          id: messageId
        });
        if (options == null ? void 0 : options.onprogress) {
          this._progressHandlers.set(messageId, options.onprogress);
          jsonrpcRequest.params = __spreadProps(__spreadValues({}, request.params), {
            _meta: __spreadProps(__spreadValues({}, ((_c2 = request.params) == null ? void 0 : _c2._meta) || {}), {
              progressToken: messageId
            })
          });
        }
        if (task) {
          jsonrpcRequest.params = __spreadProps(__spreadValues({}, jsonrpcRequest.params), {
            task
          });
        }
        if (relatedTask) {
          jsonrpcRequest.params = __spreadProps(__spreadValues({}, jsonrpcRequest.params), {
            _meta: __spreadProps(__spreadValues({}, ((_d2 = jsonrpcRequest.params) == null ? void 0 : _d2._meta) || {}), {
              [RELATED_TASK_META_KEY]: relatedTask
            })
          });
        }
        const cancel = (reason) => {
          var _a4;
          this._responseHandlers.delete(messageId);
          this._progressHandlers.delete(messageId);
          this._cleanupTimeout(messageId);
          (_a4 = this._transport) == null ? void 0 : _a4.send({
            jsonrpc: "2.0",
            method: "notifications/cancelled",
            params: {
              requestId: messageId,
              reason: String(reason)
            }
          }, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error3) => this._onerror(new Error(`Failed to send cancellation: ${error3}`)));
          const error2 = reason instanceof McpError ? reason : new McpError(ErrorCode.RequestTimeout, String(reason));
          reject(error2);
        };
        this._responseHandlers.set(messageId, (response) => {
          var _a4;
          if ((_a4 = options == null ? void 0 : options.signal) == null ? void 0 : _a4.aborted) {
            return;
          }
          if (response instanceof Error) {
            return reject(response);
          }
          try {
            const parseResult = safeParse$1(resultSchema, response.result);
            if (!parseResult.success) {
              reject(parseResult.error);
            } else {
              resolve2(parseResult.data);
            }
          } catch (error2) {
            reject(error2);
          }
        });
        (_e = options == null ? void 0 : options.signal) == null ? void 0 : _e.addEventListener("abort", () => {
          var _a4;
          cancel((_a4 = options == null ? void 0 : options.signal) == null ? void 0 : _a4.reason);
        });
        const timeout = (_f = options == null ? void 0 : options.timeout) != null ? _f : DEFAULT_REQUEST_TIMEOUT_MSEC;
        const timeoutHandler = () => cancel(McpError.fromError(ErrorCode.RequestTimeout, "Request timed out", { timeout }));
        this._setupTimeout(messageId, timeout, options == null ? void 0 : options.maxTotalTimeout, timeoutHandler, (_g = options == null ? void 0 : options.resetTimeoutOnProgress) != null ? _g : false);
        const relatedTaskId = relatedTask == null ? void 0 : relatedTask.taskId;
        if (relatedTaskId) {
          const responseResolver = (response) => {
            const handler = this._responseHandlers.get(messageId);
            if (handler) {
              handler(response);
            } else {
              this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`));
            }
          };
          this._requestResolvers.set(messageId, responseResolver);
          this._enqueueTaskMessage(relatedTaskId, {
            type: "request",
            message: jsonrpcRequest,
            timestamp: Date.now()
          }).catch((error2) => {
            this._cleanupTimeout(messageId);
            reject(error2);
          });
        } else {
          this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error2) => {
            this._cleanupTimeout(messageId);
            reject(error2);
          });
        }
      });
    }
    /**
     * Gets the current status of a task.
     *
     * @experimental Use `client.experimental.tasks.getTask()` to access this method.
     */
    getTask(params, options) {
      return __async(this, null, function* () {
        return this.request({ method: "tasks/get", params }, GetTaskResultSchema, options);
      });
    }
    /**
     * Retrieves the result of a completed task.
     *
     * @experimental Use `client.experimental.tasks.getTaskResult()` to access this method.
     */
    getTaskResult(params, resultSchema, options) {
      return __async(this, null, function* () {
        return this.request({ method: "tasks/result", params }, resultSchema, options);
      });
    }
    /**
     * Lists tasks, optionally starting from a pagination cursor.
     *
     * @experimental Use `client.experimental.tasks.listTasks()` to access this method.
     */
    listTasks(params, options) {
      return __async(this, null, function* () {
        return this.request({ method: "tasks/list", params }, ListTasksResultSchema, options);
      });
    }
    /**
     * Cancels a specific task.
     *
     * @experimental Use `client.experimental.tasks.cancelTask()` to access this method.
     */
    cancelTask(params, options) {
      return __async(this, null, function* () {
        return this.request({ method: "tasks/cancel", params }, CancelTaskResultSchema, options);
      });
    }
    /**
     * Emits a notification, which is a one-way message that does not expect a response.
     */
    notification(notification, options) {
      return __async(this, null, function* () {
        var _a3, _b2, _c2, _d2, _e;
        if (!this._transport) {
          throw new Error("Not connected");
        }
        this.assertNotificationCapability(notification.method);
        const relatedTaskId = (_a3 = options == null ? void 0 : options.relatedTask) == null ? void 0 : _a3.taskId;
        if (relatedTaskId) {
          const jsonrpcNotification2 = __spreadProps(__spreadValues({}, notification), {
            jsonrpc: "2.0",
            params: __spreadProps(__spreadValues({}, notification.params), {
              _meta: __spreadProps(__spreadValues({}, ((_b2 = notification.params) == null ? void 0 : _b2._meta) || {}), {
                [RELATED_TASK_META_KEY]: options.relatedTask
              })
            })
          });
          yield this._enqueueTaskMessage(relatedTaskId, {
            type: "notification",
            message: jsonrpcNotification2,
            timestamp: Date.now()
          });
          return;
        }
        const debouncedMethods = (_d2 = (_c2 = this._options) == null ? void 0 : _c2.debouncedNotificationMethods) != null ? _d2 : [];
        const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !(options == null ? void 0 : options.relatedRequestId) && !(options == null ? void 0 : options.relatedTask);
        if (canDebounce) {
          if (this._pendingDebouncedNotifications.has(notification.method)) {
            return;
          }
          this._pendingDebouncedNotifications.add(notification.method);
          Promise.resolve().then(() => {
            var _a4, _b3;
            this._pendingDebouncedNotifications.delete(notification.method);
            if (!this._transport) {
              return;
            }
            let jsonrpcNotification2 = __spreadProps(__spreadValues({}, notification), {
              jsonrpc: "2.0"
            });
            if (options == null ? void 0 : options.relatedTask) {
              jsonrpcNotification2 = __spreadProps(__spreadValues({}, jsonrpcNotification2), {
                params: __spreadProps(__spreadValues({}, jsonrpcNotification2.params), {
                  _meta: __spreadProps(__spreadValues({}, ((_a4 = jsonrpcNotification2.params) == null ? void 0 : _a4._meta) || {}), {
                    [RELATED_TASK_META_KEY]: options.relatedTask
                  })
                })
              });
            }
            (_b3 = this._transport) == null ? void 0 : _b3.send(jsonrpcNotification2, options).catch((error2) => this._onerror(error2));
          });
          return;
        }
        let jsonrpcNotification = __spreadProps(__spreadValues({}, notification), {
          jsonrpc: "2.0"
        });
        if (options == null ? void 0 : options.relatedTask) {
          jsonrpcNotification = __spreadProps(__spreadValues({}, jsonrpcNotification), {
            params: __spreadProps(__spreadValues({}, jsonrpcNotification.params), {
              _meta: __spreadProps(__spreadValues({}, ((_e = jsonrpcNotification.params) == null ? void 0 : _e._meta) || {}), {
                [RELATED_TASK_META_KEY]: options.relatedTask
              })
            })
          });
        }
        yield this._transport.send(jsonrpcNotification, options);
      });
    }
    /**
     * Registers a handler to invoke when this protocol object receives a request with the given method.
     *
     * Note that this will replace any previous request handler for the same method.
     */
    setRequestHandler(requestSchema, handler) {
      const method = getMethodLiteral(requestSchema);
      this.assertRequestHandlerCapability(method);
      this._requestHandlers.set(method, (request, extra) => {
        const parsed = parseWithCompat(requestSchema, request);
        return Promise.resolve(handler(parsed, extra));
      });
    }
    /**
     * Removes the request handler for the given method.
     */
    removeRequestHandler(method) {
      this._requestHandlers.delete(method);
    }
    /**
     * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed.
     */
    assertCanSetRequestHandler(method) {
      if (this._requestHandlers.has(method)) {
        throw new Error(`A request handler for ${method} already exists, which would be overridden`);
      }
    }
    /**
     * Registers a handler to invoke when this protocol object receives a notification with the given method.
     *
     * Note that this will replace any previous notification handler for the same method.
     */
    setNotificationHandler(notificationSchema, handler) {
      const method = getMethodLiteral(notificationSchema);
      this._notificationHandlers.set(method, (notification) => {
        const parsed = parseWithCompat(notificationSchema, notification);
        return Promise.resolve(handler(parsed));
      });
    }
    /**
     * Removes the notification handler for the given method.
     */
    removeNotificationHandler(method) {
      this._notificationHandlers.delete(method);
    }
    /**
     * Cleans up the progress handler associated with a task.
     * This should be called when a task reaches a terminal status.
     */
    _cleanupTaskProgressHandler(taskId) {
      const progressToken = this._taskProgressTokens.get(taskId);
      if (progressToken !== void 0) {
        this._progressHandlers.delete(progressToken);
        this._taskProgressTokens.delete(taskId);
      }
    }
    /**
     * Enqueues a task-related message for side-channel delivery via tasks/result.
     * @param taskId The task ID to associate the message with
     * @param message The message to enqueue
     * @param sessionId Optional session ID for binding the operation to a specific session
     * @throws Error if taskStore is not configured or if enqueue fails (e.g., queue overflow)
     *
     * Note: If enqueue fails, it's the TaskMessageQueue implementation's responsibility to handle
     * the error appropriately (e.g., by failing the task, logging, etc.). The Protocol layer
     * simply propagates the error.
     */
    _enqueueTaskMessage(taskId, message, sessionId) {
      return __async(this, null, function* () {
        var _a3;
        if (!this._taskStore || !this._taskMessageQueue) {
          throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");
        }
        const maxQueueSize = (_a3 = this._options) == null ? void 0 : _a3.maxTaskQueueSize;
        yield this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize);
      });
    }
    /**
     * Clears the message queue for a task and rejects any pending request resolvers.
     * @param taskId The task ID whose queue should be cleared
     * @param sessionId Optional session ID for binding the operation to a specific session
     */
    _clearTaskQueue(taskId, sessionId) {
      return __async(this, null, function* () {
        if (this._taskMessageQueue) {
          const messages = yield this._taskMessageQueue.dequeueAll(taskId, sessionId);
          for (const message of messages) {
            if (message.type === "request" && isJSONRPCRequest(message.message)) {
              const requestId = message.message.id;
              const resolver = this._requestResolvers.get(requestId);
              if (resolver) {
                resolver(new McpError(ErrorCode.InternalError, "Task cancelled or completed"));
                this._requestResolvers.delete(requestId);
              } else {
                this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`));
              }
            }
          }
        }
      });
    }
    /**
     * Waits for a task update (new messages or status change) with abort signal support.
     * Uses polling to check for updates at the task's configured poll interval.
     * @param taskId The task ID to wait for
     * @param signal Abort signal to cancel the wait
     * @returns Promise that resolves when an update occurs or rejects if aborted
     */
    _waitForTaskUpdate(taskId, signal) {
      return __async(this, null, function* () {
        var _a3, _b2, _c2;
        let interval = (_b2 = (_a3 = this._options) == null ? void 0 : _a3.defaultTaskPollInterval) != null ? _b2 : 1e3;
        try {
          const task = yield (_c2 = this._taskStore) == null ? void 0 : _c2.getTask(taskId);
          if (task == null ? void 0 : task.pollInterval) {
            interval = task.pollInterval;
          }
        } catch (e) {
        }
        return new Promise((resolve2, reject) => {
          if (signal.aborted) {
            reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
            return;
          }
          const timeoutId = setTimeout(resolve2, interval);
          signal.addEventListener("abort", () => {
            clearTimeout(timeoutId);
            reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
          }, { once: true });
        });
      });
    }
    requestTaskStore(request, sessionId) {
      const taskStore = this._taskStore;
      if (!taskStore) {
        throw new Error("No task store configured");
      }
      return {
        createTask: (taskParams) => __async(this, null, function* () {
          if (!request) {
            throw new Error("No request provided");
          }
          return yield taskStore.createTask(taskParams, request.id, {
            method: request.method,
            params: request.params
          }, sessionId);
        }),
        getTask: (taskId) => __async(this, null, function* () {
          const task = yield taskStore.getTask(taskId, sessionId);
          if (!task) {
            throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found");
          }
          return task;
        }),
        storeTaskResult: (taskId, status, result2) => __async(this, null, function* () {
          yield taskStore.storeTaskResult(taskId, status, result2, sessionId);
          const task = yield taskStore.getTask(taskId, sessionId);
          if (task) {
            const notification = TaskStatusNotificationSchema.parse({
              method: "notifications/tasks/status",
              params: task
            });
            yield this.notification(notification);
            if (isTerminal(task.status)) {
              this._cleanupTaskProgressHandler(taskId);
            }
          }
        }),
        getTaskResult: (taskId) => {
          return taskStore.getTaskResult(taskId, sessionId);
        },
        updateTaskStatus: (taskId, status, statusMessage) => __async(this, null, function* () {
          const task = yield taskStore.getTask(taskId, sessionId);
          if (!task) {
            throw new McpError(ErrorCode.InvalidParams, `Task "${taskId}" not found - it may have been cleaned up`);
          }
          if (isTerminal(task.status)) {
            throw new McpError(ErrorCode.InvalidParams, `Cannot update task "${taskId}" from terminal status "${task.status}" to "${status}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);
          }
          yield taskStore.updateTaskStatus(taskId, status, statusMessage, sessionId);
          const updatedTask = yield taskStore.getTask(taskId, sessionId);
          if (updatedTask) {
            const notification = TaskStatusNotificationSchema.parse({
              method: "notifications/tasks/status",
              params: updatedTask
            });
            yield this.notification(notification);
            if (isTerminal(updatedTask.status)) {
              this._cleanupTaskProgressHandler(taskId);
            }
          }
        }),
        listTasks: (cursor) => {
          return taskStore.listTasks(cursor, sessionId);
        }
      };
    }
  }
  function isPlainObject(value) {
    return value !== null && typeof value === "object" && !Array.isArray(value);
  }
  function mergeCapabilities(base, additional) {
    const result2 = __spreadValues({}, base);
    for (const key in additional) {
      const k = key;
      const addValue = additional[k];
      if (addValue === void 0)
        continue;
      const baseValue = result2[k];
      if (isPlainObject(baseValue) && isPlainObject(addValue)) {
        result2[k] = __spreadValues(__spreadValues({}, baseValue), addValue);
      } else {
        result2[k] = addValue;
      }
    }
    return result2;
  }
  function getDefaultExportFromCjs$1(x) {
    return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
  }
  function getAugmentedNamespace(n) {
    if (Object.prototype.hasOwnProperty.call(n, "__esModule")) return n;
    var f = n.default;
    if (typeof f == "function") {
      var a = function a2() {
        var isInstance = false;
        try {
          isInstance = this instanceof a2;
        } catch (e) {
        }
        if (isInstance) {
          return Reflect.construct(f, arguments, this.constructor);
        }
        return f.apply(this, arguments);
      };
      a.prototype = f.prototype;
    } else a = {};
    Object.defineProperty(a, "__esModule", { value: true });
    Object.keys(n).forEach(function(k) {
      var d = Object.getOwnPropertyDescriptor(n, k);
      Object.defineProperty(a, k, d.get ? d : {
        enumerable: true,
        get: function() {
          return n[k];
        }
      });
    });
    return a;
  }
  var ajv = { exports: {} };
  var core$1 = {};
  var validate = {};
  var boolSchema = {};
  var errors = {};
  var codegen = {};
  var code$2 = {};
  var hasRequiredCode$1;
  function requireCode$1() {
    if (hasRequiredCode$1) return code$2;
    hasRequiredCode$1 = 1;
    (function(exports$12) {
      Object.defineProperty(exports$12, "__esModule", { value: true });
      exports$12.regexpCode = exports$12.getEsmExportName = exports$12.getProperty = exports$12.safeStringify = exports$12.stringify = exports$12.strConcat = exports$12.addCodeArg = exports$12.str = exports$12._ = exports$12.nil = exports$12._Code = exports$12.Name = exports$12.IDENTIFIER = exports$12._CodeOrName = void 0;
      class _CodeOrName {
      }
      exports$12._CodeOrName = _CodeOrName;
      exports$12.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
      class Name extends _CodeOrName {
        constructor(s) {
          super();
          if (!exports$12.IDENTIFIER.test(s))
            throw new Error("CodeGen: name must be a valid identifier");
          this.str = s;
        }
        toString() {
          return this.str;
        }
        emptyStr() {
          return false;
        }
        get names() {
          return { [this.str]: 1 };
        }
      }
      exports$12.Name = Name;
      class _Code extends _CodeOrName {
        constructor(code2) {
          super();
          this._items = typeof code2 === "string" ? [code2] : code2;
        }
        toString() {
          return this.str;
        }
        emptyStr() {
          if (this._items.length > 1)
            return false;
          const item = this._items[0];
          return item === "" || item === '""';
        }
        get str() {
          var _a3;
          return (_a3 = this._str) !== null && _a3 !== void 0 ? _a3 : this._str = this._items.reduce((s, c) => `${s}${c}`, "");
        }
        get names() {
          var _a3;
          return (_a3 = this._names) !== null && _a3 !== void 0 ? _a3 : this._names = this._items.reduce((names2, c) => {
            if (c instanceof Name)
              names2[c.str] = (names2[c.str] || 0) + 1;
            return names2;
          }, {});
        }
      }
      exports$12._Code = _Code;
      exports$12.nil = new _Code("");
      function _(strs, ...args) {
        const code2 = [strs[0]];
        let i2 = 0;
        while (i2 < args.length) {
          addCodeArg(code2, args[i2]);
          code2.push(strs[++i2]);
        }
        return new _Code(code2);
      }
      exports$12._ = _;
      const plus = new _Code("+");
      function str(strs, ...args) {
        const expr = [safeStringify(strs[0])];
        let i2 = 0;
        while (i2 < args.length) {
          expr.push(plus);
          addCodeArg(expr, args[i2]);
          expr.push(plus, safeStringify(strs[++i2]));
        }
        optimize(expr);
        return new _Code(expr);
      }
      exports$12.str = str;
      function addCodeArg(code2, arg) {
        if (arg instanceof _Code)
          code2.push(...arg._items);
        else if (arg instanceof Name)
          code2.push(arg);
        else
          code2.push(interpolate(arg));
      }
      exports$12.addCodeArg = addCodeArg;
      function optimize(expr) {
        let i2 = 1;
        while (i2 < expr.length - 1) {
          if (expr[i2] === plus) {
            const res = mergeExprItems(expr[i2 - 1], expr[i2 + 1]);
            if (res !== void 0) {
              expr.splice(i2 - 1, 3, res);
              continue;
            }
            expr[i2++] = "+";
          }
          i2++;
        }
      }
      function mergeExprItems(a, b) {
        if (b === '""')
          return a;
        if (a === '""')
          return b;
        if (typeof a == "string") {
          if (b instanceof Name || a[a.length - 1] !== '"')
            return;
          if (typeof b != "string")
            return `${a.slice(0, -1)}${b}"`;
          if (b[0] === '"')
            return a.slice(0, -1) + b.slice(1);
          return;
        }
        if (typeof b == "string" && b[0] === '"' && !(a instanceof Name))
          return `"${a}${b.slice(1)}`;
        return;
      }
      function strConcat(c1, c2) {
        return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`;
      }
      exports$12.strConcat = strConcat;
      function interpolate(x) {
        return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x);
      }
      function stringify(x) {
        return new _Code(safeStringify(x));
      }
      exports$12.stringify = stringify;
      function safeStringify(x) {
        return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
      }
      exports$12.safeStringify = safeStringify;
      function getProperty(key) {
        return typeof key == "string" && exports$12.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`;
      }
      exports$12.getProperty = getProperty;
      function getEsmExportName(key) {
        if (typeof key == "string" && exports$12.IDENTIFIER.test(key)) {
          return new _Code(`${key}`);
        }
        throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`);
      }
      exports$12.getEsmExportName = getEsmExportName;
      function regexpCode(rx) {
        return new _Code(rx.toString());
      }
      exports$12.regexpCode = regexpCode;
    })(code$2);
    return code$2;
  }
  var scope = {};
  var hasRequiredScope;
  function requireScope() {
    if (hasRequiredScope) return scope;
    hasRequiredScope = 1;
    (function(exports$12) {
      Object.defineProperty(exports$12, "__esModule", { value: true });
      exports$12.ValueScope = exports$12.ValueScopeName = exports$12.Scope = exports$12.varKinds = exports$12.UsedValueState = void 0;
      const code_1 = requireCode$1();
      class ValueError extends Error {
        constructor(name2) {
          super(`CodeGen: "code" for ${name2} not defined`);
          this.value = name2.value;
        }
      }
      var UsedValueState;
      (function(UsedValueState2) {
        UsedValueState2[UsedValueState2["Started"] = 0] = "Started";
        UsedValueState2[UsedValueState2["Completed"] = 1] = "Completed";
      })(UsedValueState || (exports$12.UsedValueState = UsedValueState = {}));
      exports$12.varKinds = {
        const: new code_1.Name("const"),
        let: new code_1.Name("let"),
        var: new code_1.Name("var")
      };
      class Scope {
        constructor({ prefixes, parent } = {}) {
          this._names = {};
          this._prefixes = prefixes;
          this._parent = parent;
        }
        toName(nameOrPrefix) {
          return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix);
        }
        name(prefix) {
          return new code_1.Name(this._newName(prefix));
        }
        _newName(prefix) {
          const ng = this._names[prefix] || this._nameGroup(prefix);
          return `${prefix}${ng.index++}`;
        }
        _nameGroup(prefix) {
          var _a3, _b2;
          if (((_b2 = (_a3 = this._parent) === null || _a3 === void 0 ? void 0 : _a3._prefixes) === null || _b2 === void 0 ? void 0 : _b2.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) {
            throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`);
          }
          return this._names[prefix] = { prefix, index: 0 };
        }
      }
      exports$12.Scope = Scope;
      class ValueScopeName extends code_1.Name {
        constructor(prefix, nameStr) {
          super(nameStr);
          this.prefix = prefix;
        }
        setValue(value, { property, itemIndex }) {
          this.value = value;
          this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`;
        }
      }
      exports$12.ValueScopeName = ValueScopeName;
      const line = (0, code_1._)`\n`;
      class ValueScope extends Scope {
        constructor(opts) {
          super(opts);
          this._values = {};
          this._scope = opts.scope;
          this.opts = __spreadProps(__spreadValues({}, opts), { _n: opts.lines ? line : code_1.nil });
        }
        get() {
          return this._scope;
        }
        name(prefix) {
          return new ValueScopeName(prefix, this._newName(prefix));
        }
        value(nameOrPrefix, value) {
          var _a3;
          if (value.ref === void 0)
            throw new Error("CodeGen: ref must be passed in value");
          const name2 = this.toName(nameOrPrefix);
          const { prefix } = name2;
          const valueKey = (_a3 = value.key) !== null && _a3 !== void 0 ? _a3 : value.ref;
          let vs = this._values[prefix];
          if (vs) {
            const _name = vs.get(valueKey);
            if (_name)
              return _name;
          } else {
            vs = this._values[prefix] = /* @__PURE__ */ new Map();
          }
          vs.set(valueKey, name2);
          const s = this._scope[prefix] || (this._scope[prefix] = []);
          const itemIndex = s.length;
          s[itemIndex] = value.ref;
          name2.setValue(value, { property: prefix, itemIndex });
          return name2;
        }
        getValue(prefix, keyOrRef) {
          const vs = this._values[prefix];
          if (!vs)
            return;
          return vs.get(keyOrRef);
        }
        scopeRefs(scopeName, values = this._values) {
          return this._reduceValues(values, (name2) => {
            if (name2.scopePath === void 0)
              throw new Error(`CodeGen: name "${name2}" has no value`);
            return (0, code_1._)`${scopeName}${name2.scopePath}`;
          });
        }
        scopeCode(values = this._values, usedValues, getCode) {
          return this._reduceValues(values, (name2) => {
            if (name2.value === void 0)
              throw new Error(`CodeGen: name "${name2}" has no value`);
            return name2.value.code;
          }, usedValues, getCode);
        }
        _reduceValues(values, valueCode, usedValues = {}, getCode) {
          let code2 = code_1.nil;
          for (const prefix in values) {
            const vs = values[prefix];
            if (!vs)
              continue;
            const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map();
            vs.forEach((name2) => {
              if (nameSet.has(name2))
                return;
              nameSet.set(name2, UsedValueState.Started);
              let c = valueCode(name2);
              if (c) {
                const def = this.opts.es5 ? exports$12.varKinds.var : exports$12.varKinds.const;
                code2 = (0, code_1._)`${code2}${def} ${name2} = ${c};${this.opts._n}`;
              } else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name2)) {
                code2 = (0, code_1._)`${code2}${c}${this.opts._n}`;
              } else {
                throw new ValueError(name2);
              }
              nameSet.set(name2, UsedValueState.Completed);
            });
          }
          return code2;
        }
      }
      exports$12.ValueScope = ValueScope;
    })(scope);
    return scope;
  }
  var hasRequiredCodegen;
  function requireCodegen() {
    if (hasRequiredCodegen) return codegen;
    hasRequiredCodegen = 1;
    (function(exports$12) {
      Object.defineProperty(exports$12, "__esModule", { value: true });
      exports$12.or = exports$12.and = exports$12.not = exports$12.CodeGen = exports$12.operators = exports$12.varKinds = exports$12.ValueScopeName = exports$12.ValueScope = exports$12.Scope = exports$12.Name = exports$12.regexpCode = exports$12.stringify = exports$12.getProperty = exports$12.nil = exports$12.strConcat = exports$12.str = exports$12._ = void 0;
      const code_1 = requireCode$1();
      const scope_1 = requireScope();
      var code_2 = requireCode$1();
      Object.defineProperty(exports$12, "_", { enumerable: true, get: function() {
        return code_2._;
      } });
      Object.defineProperty(exports$12, "str", { enumerable: true, get: function() {
        return code_2.str;
      } });
      Object.defineProperty(exports$12, "strConcat", { enumerable: true, get: function() {
        return code_2.strConcat;
      } });
      Object.defineProperty(exports$12, "nil", { enumerable: true, get: function() {
        return code_2.nil;
      } });
      Object.defineProperty(exports$12, "getProperty", { enumerable: true, get: function() {
        return code_2.getProperty;
      } });
      Object.defineProperty(exports$12, "stringify", { enumerable: true, get: function() {
        return code_2.stringify;
      } });
      Object.defineProperty(exports$12, "regexpCode", { enumerable: true, get: function() {
        return code_2.regexpCode;
      } });
      Object.defineProperty(exports$12, "Name", { enumerable: true, get: function() {
        return code_2.Name;
      } });
      var scope_2 = requireScope();
      Object.defineProperty(exports$12, "Scope", { enumerable: true, get: function() {
        return scope_2.Scope;
      } });
      Object.defineProperty(exports$12, "ValueScope", { enumerable: true, get: function() {
        return scope_2.ValueScope;
      } });
      Object.defineProperty(exports$12, "ValueScopeName", { enumerable: true, get: function() {
        return scope_2.ValueScopeName;
      } });
      Object.defineProperty(exports$12, "varKinds", { enumerable: true, get: function() {
        return scope_2.varKinds;
      } });
      exports$12.operators = {
        GT: new code_1._Code(">"),
        GTE: new code_1._Code(">="),
        LT: new code_1._Code("<"),
        LTE: new code_1._Code("<="),
        EQ: new code_1._Code("==="),
        NEQ: new code_1._Code("!=="),
        NOT: new code_1._Code("!"),
        OR: new code_1._Code("||"),
        AND: new code_1._Code("&&"),
        ADD: new code_1._Code("+")
      };
      class Node {
        optimizeNodes() {
          return this;
        }
        optimizeNames(_names, _constants) {
          return this;
        }
      }
      class Def extends Node {
        constructor(varKind, name2, rhs) {
          super();
          this.varKind = varKind;
          this.name = name2;
          this.rhs = rhs;
        }
        render({ es5, _n }) {
          const varKind = es5 ? scope_1.varKinds.var : this.varKind;
          const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`;
          return `${varKind} ${this.name}${rhs};` + _n;
        }
        optimizeNames(names2, constants) {
          if (!names2[this.name.str])
            return;
          if (this.rhs)
            this.rhs = optimizeExpr(this.rhs, names2, constants);
          return this;
        }
        get names() {
          return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {};
        }
      }
      class Assign extends Node {
        constructor(lhs, rhs, sideEffects) {
          super();
          this.lhs = lhs;
          this.rhs = rhs;
          this.sideEffects = sideEffects;
        }
        render({ _n }) {
          return `${this.lhs} = ${this.rhs};` + _n;
        }
        optimizeNames(names2, constants) {
          if (this.lhs instanceof code_1.Name && !names2[this.lhs.str] && !this.sideEffects)
            return;
          this.rhs = optimizeExpr(this.rhs, names2, constants);
          return this;
        }
        get names() {
          const names2 = this.lhs instanceof code_1.Name ? {} : __spreadValues({}, this.lhs.names);
          return addExprNames(names2, this.rhs);
        }
      }
      class AssignOp extends Assign {
        constructor(lhs, op, rhs, sideEffects) {
          super(lhs, rhs, sideEffects);
          this.op = op;
        }
        render({ _n }) {
          return `${this.lhs} ${this.op}= ${this.rhs};` + _n;
        }
      }
      class Label extends Node {
        constructor(label) {
          super();
          this.label = label;
          this.names = {};
        }
        render({ _n }) {
          return `${this.label}:` + _n;
        }
      }
      class Break extends Node {
        constructor(label) {
          super();
          this.label = label;
          this.names = {};
        }
        render({ _n }) {
          const label = this.label ? ` ${this.label}` : "";
          return `break${label};` + _n;
        }
      }
      class Throw extends Node {
        constructor(error2) {
          super();
          this.error = error2;
        }
        render({ _n }) {
          return `throw ${this.error};` + _n;
        }
        get names() {
          return this.error.names;
        }
      }
      class AnyCode extends Node {
        constructor(code2) {
          super();
          this.code = code2;
        }
        render({ _n }) {
          return `${this.code};` + _n;
        }
        optimizeNodes() {
          return `${this.code}` ? this : void 0;
        }
        optimizeNames(names2, constants) {
          this.code = optimizeExpr(this.code, names2, constants);
          return this;
        }
        get names() {
          return this.code instanceof code_1._CodeOrName ? this.code.names : {};
        }
      }
      class ParentNode extends Node {
        constructor(nodes = []) {
          super();
          this.nodes = nodes;
        }
        render(opts) {
          return this.nodes.reduce((code2, n) => code2 + n.render(opts), "");
        }
        optimizeNodes() {
          const { nodes } = this;
          let i2 = nodes.length;
          while (i2--) {
            const n = nodes[i2].optimizeNodes();
            if (Array.isArray(n))
              nodes.splice(i2, 1, ...n);
            else if (n)
              nodes[i2] = n;
            else
              nodes.splice(i2, 1);
          }
          return nodes.length > 0 ? this : void 0;
        }
        optimizeNames(names2, constants) {
          const { nodes } = this;
          let i2 = nodes.length;
          while (i2--) {
            const n = nodes[i2];
            if (n.optimizeNames(names2, constants))
              continue;
            subtractNames(names2, n.names);
            nodes.splice(i2, 1);
          }
          return nodes.length > 0 ? this : void 0;
        }
        get names() {
          return this.nodes.reduce((names2, n) => addNames(names2, n.names), {});
        }
      }
      class BlockNode extends ParentNode {
        render(opts) {
          return "{" + opts._n + super.render(opts) + "}" + opts._n;
        }
      }
      class Root extends ParentNode {
      }
      class Else extends BlockNode {
      }
      Else.kind = "else";
      class If extends BlockNode {
        constructor(condition, nodes) {
          super(nodes);
          this.condition = condition;
        }
        render(opts) {
          let code2 = `if(${this.condition})` + super.render(opts);
          if (this.else)
            code2 += "else " + this.else.render(opts);
          return code2;
        }
        optimizeNodes() {
          super.optimizeNodes();
          const cond = this.condition;
          if (cond === true)
            return this.nodes;
          let e = this.else;
          if (e) {
            const ns = e.optimizeNodes();
            e = this.else = Array.isArray(ns) ? new Else(ns) : ns;
          }
          if (e) {
            if (cond === false)
              return e instanceof If ? e : e.nodes;
            if (this.nodes.length)
              return this;
            return new If(not2(cond), e instanceof If ? [e] : e.nodes);
          }
          if (cond === false || !this.nodes.length)
            return void 0;
          return this;
        }
        optimizeNames(names2, constants) {
          var _a3;
          this.else = (_a3 = this.else) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names2, constants);
          if (!(super.optimizeNames(names2, constants) || this.else))
            return;
          this.condition = optimizeExpr(this.condition, names2, constants);
          return this;
        }
        get names() {
          const names2 = super.names;
          addExprNames(names2, this.condition);
          if (this.else)
            addNames(names2, this.else.names);
          return names2;
        }
      }
      If.kind = "if";
      class For extends BlockNode {
      }
      For.kind = "for";
      class ForLoop extends For {
        constructor(iteration) {
          super();
          this.iteration = iteration;
        }
        render(opts) {
          return `for(${this.iteration})` + super.render(opts);
        }
        optimizeNames(names2, constants) {
          if (!super.optimizeNames(names2, constants))
            return;
          this.iteration = optimizeExpr(this.iteration, names2, constants);
          return this;
        }
        get names() {
          return addNames(super.names, this.iteration.names);
        }
      }
      class ForRange extends For {
        constructor(varKind, name2, from, to) {
          super();
          this.varKind = varKind;
          this.name = name2;
          this.from = from;
          this.to = to;
        }
        render(opts) {
          const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind;
          const { name: name2, from, to } = this;
          return `for(${varKind} ${name2}=${from}; ${name2}<${to}; ${name2}++)` + super.render(opts);
        }
        get names() {
          const names2 = addExprNames(super.names, this.from);
          return addExprNames(names2, this.to);
        }
      }
      class ForIter extends For {
        constructor(loop, varKind, name2, iterable) {
          super();
          this.loop = loop;
          this.varKind = varKind;
          this.name = name2;
          this.iterable = iterable;
        }
        render(opts) {
          return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
        }
        optimizeNames(names2, constants) {
          if (!super.optimizeNames(names2, constants))
            return;
          this.iterable = optimizeExpr(this.iterable, names2, constants);
          return this;
        }
        get names() {
          return addNames(super.names, this.iterable.names);
        }
      }
      class Func extends BlockNode {
        constructor(name2, args, async) {
          super();
          this.name = name2;
          this.args = args;
          this.async = async;
        }
        render(opts) {
          const _async = this.async ? "async " : "";
          return `${_async}function ${this.name}(${this.args})` + super.render(opts);
        }
      }
      Func.kind = "func";
      class Return extends ParentNode {
        render(opts) {
          return "return " + super.render(opts);
        }
      }
      Return.kind = "return";
      class Try extends BlockNode {
        render(opts) {
          let code2 = "try" + super.render(opts);
          if (this.catch)
            code2 += this.catch.render(opts);
          if (this.finally)
            code2 += this.finally.render(opts);
          return code2;
        }
        optimizeNodes() {
          var _a3, _b2;
          super.optimizeNodes();
          (_a3 = this.catch) === null || _a3 === void 0 ? void 0 : _a3.optimizeNodes();
          (_b2 = this.finally) === null || _b2 === void 0 ? void 0 : _b2.optimizeNodes();
          return this;
        }
        optimizeNames(names2, constants) {
          var _a3, _b2;
          super.optimizeNames(names2, constants);
          (_a3 = this.catch) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names2, constants);
          (_b2 = this.finally) === null || _b2 === void 0 ? void 0 : _b2.optimizeNames(names2, constants);
          return this;
        }
        get names() {
          const names2 = super.names;
          if (this.catch)
            addNames(names2, this.catch.names);
          if (this.finally)
            addNames(names2, this.finally.names);
          return names2;
        }
      }
      class Catch extends BlockNode {
        constructor(error2) {
          super();
          this.error = error2;
        }
        render(opts) {
          return `catch(${this.error})` + super.render(opts);
        }
      }
      Catch.kind = "catch";
      class Finally extends BlockNode {
        render(opts) {
          return "finally" + super.render(opts);
        }
      }
      Finally.kind = "finally";
      class CodeGen {
        constructor(extScope, opts = {}) {
          this._values = {};
          this._blockStarts = [];
          this._constants = {};
          this.opts = __spreadProps(__spreadValues({}, opts), { _n: opts.lines ? "\n" : "" });
          this._extScope = extScope;
          this._scope = new scope_1.Scope({ parent: extScope });
          this._nodes = [new Root()];
        }
        toString() {
          return this._root.render(this.opts);
        }
        // returns unique name in the internal scope
        name(prefix) {
          return this._scope.name(prefix);
        }
        // reserves unique name in the external scope
        scopeName(prefix) {
          return this._extScope.name(prefix);
        }
        // reserves unique name in the external scope and assigns value to it
        scopeValue(prefixOrName, value) {
          const name2 = this._extScope.value(prefixOrName, value);
          const vs = this._values[name2.prefix] || (this._values[name2.prefix] = /* @__PURE__ */ new Set());
          vs.add(name2);
          return name2;
        }
        getScopeValue(prefix, keyOrRef) {
          return this._extScope.getValue(prefix, keyOrRef);
        }
        // return code that assigns values in the external scope to the names that are used internally
        // (same names that were returned by gen.scopeName or gen.scopeValue)
        scopeRefs(scopeName) {
          return this._extScope.scopeRefs(scopeName, this._values);
        }
        scopeCode() {
          return this._extScope.scopeCode(this._values);
        }
        _def(varKind, nameOrPrefix, rhs, constant) {
          const name2 = this._scope.toName(nameOrPrefix);
          if (rhs !== void 0 && constant)
            this._constants[name2.str] = rhs;
          this._leafNode(new Def(varKind, name2, rhs));
          return name2;
        }
        // `const` declaration (`var` in es5 mode)
        const(nameOrPrefix, rhs, _constant) {
          return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant);
        }
        // `let` declaration with optional assignment (`var` in es5 mode)
        let(nameOrPrefix, rhs, _constant) {
          return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant);
        }
        // `var` declaration with optional assignment
        var(nameOrPrefix, rhs, _constant) {
          return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant);
        }
        // assignment code
        assign(lhs, rhs, sideEffects) {
          return this._leafNode(new Assign(lhs, rhs, sideEffects));
        }
        // `+=` code
        add(lhs, rhs) {
          return this._leafNode(new AssignOp(lhs, exports$12.operators.ADD, rhs));
        }
        // appends passed SafeExpr to code or executes Block
        code(c) {
          if (typeof c == "function")
            c();
          else if (c !== code_1.nil)
            this._leafNode(new AnyCode(c));
          return this;
        }
        // returns code for object literal for the passed argument list of key-value pairs
        object(...keyValues) {
          const code2 = ["{"];
          for (const [key, value] of keyValues) {
            if (code2.length > 1)
              code2.push(",");
            code2.push(key);
            if (key !== value || this.opts.es5) {
              code2.push(":");
              (0, code_1.addCodeArg)(code2, value);
            }
          }
          code2.push("}");
          return new code_1._Code(code2);
        }
        // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)
        if(condition, thenBody, elseBody) {
          this._blockNode(new If(condition));
          if (thenBody && elseBody) {
            this.code(thenBody).else().code(elseBody).endIf();
          } else if (thenBody) {
            this.code(thenBody).endIf();
          } else if (elseBody) {
            throw new Error('CodeGen: "else" body without "then" body');
          }
          return this;
        }
        // `else if` clause - invalid without `if` or after `else` clauses
        elseIf(condition) {
          return this._elseNode(new If(condition));
        }
        // `else` clause - only valid after `if` or `else if` clauses
        else() {
          return this._elseNode(new Else());
        }
        // end `if` statement (needed if gen.if was used only with condition)
        endIf() {
          return this._endBlockNode(If, Else);
        }
        _for(node, forBody) {
          this._blockNode(node);
          if (forBody)
            this.code(forBody).endFor();
          return this;
        }
        // a generic `for` clause (or statement if `forBody` is passed)
        for(iteration, forBody) {
          return this._for(new ForLoop(iteration), forBody);
        }
        // `for` statement for a range of values
        forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) {
          const name2 = this._scope.toName(nameOrPrefix);
          return this._for(new ForRange(varKind, name2, from, to), () => forBody(name2));
        }
        // `for-of` statement (in es5 mode replace with a normal for loop)
        forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) {
          const name2 = this._scope.toName(nameOrPrefix);
          if (this.opts.es5) {
            const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable);
            return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i2) => {
              this.var(name2, (0, code_1._)`${arr}[${i2}]`);
              forBody(name2);
            });
          }
          return this._for(new ForIter("of", varKind, name2, iterable), () => forBody(name2));
        }
        // `for-in` statement.
        // With option `ownProperties` replaced with a `for-of` loop for object keys
        forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) {
          if (this.opts.ownProperties) {
            return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody);
          }
          const name2 = this._scope.toName(nameOrPrefix);
          return this._for(new ForIter("in", varKind, name2, obj), () => forBody(name2));
        }
        // end `for` loop
        endFor() {
          return this._endBlockNode(For);
        }
        // `label` statement
        label(label) {
          return this._leafNode(new Label(label));
        }
        // `break` statement
        break(label) {
          return this._leafNode(new Break(label));
        }
        // `return` statement
        return(value) {
          const node = new Return();
          this._blockNode(node);
          this.code(value);
          if (node.nodes.length !== 1)
            throw new Error('CodeGen: "return" should have one node');
          return this._endBlockNode(Return);
        }
        // `try` statement
        try(tryBody, catchCode, finallyCode) {
          if (!catchCode && !finallyCode)
            throw new Error('CodeGen: "try" without "catch" and "finally"');
          const node = new Try();
          this._blockNode(node);
          this.code(tryBody);
          if (catchCode) {
            const error2 = this.name("e");
            this._currNode = node.catch = new Catch(error2);
            catchCode(error2);
          }
          if (finallyCode) {
            this._currNode = node.finally = new Finally();
            this.code(finallyCode);
          }
          return this._endBlockNode(Catch, Finally);
        }
        // `throw` statement
        throw(error2) {
          return this._leafNode(new Throw(error2));
        }
        // start self-balancing block
        block(body, nodeCount) {
          this._blockStarts.push(this._nodes.length);
          if (body)
            this.code(body).endBlock(nodeCount);
          return this;
        }
        // end the current self-balancing block
        endBlock(nodeCount) {
          const len2 = this._blockStarts.pop();
          if (len2 === void 0)
            throw new Error("CodeGen: not in self-balancing block");
          const toClose = this._nodes.length - len2;
          if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) {
            throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`);
          }
          this._nodes.length = len2;
          return this;
        }
        // `function` heading (or definition if funcBody is passed)
        func(name2, args = code_1.nil, async, funcBody) {
          this._blockNode(new Func(name2, args, async));
          if (funcBody)
            this.code(funcBody).endFunc();
          return this;
        }
        // end function definition
        endFunc() {
          return this._endBlockNode(Func);
        }
        optimize(n = 1) {
          while (n-- > 0) {
            this._root.optimizeNodes();
            this._root.optimizeNames(this._root.names, this._constants);
          }
        }
        _leafNode(node) {
          this._currNode.nodes.push(node);
          return this;
        }
        _blockNode(node) {
          this._currNode.nodes.push(node);
          this._nodes.push(node);
        }
        _endBlockNode(N1, N2) {
          const n = this._currNode;
          if (n instanceof N1 || N2 && n instanceof N2) {
            this._nodes.pop();
            return this;
          }
          throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`);
        }
        _elseNode(node) {
          const n = this._currNode;
          if (!(n instanceof If)) {
            throw new Error('CodeGen: "else" without "if"');
          }
          this._currNode = n.else = node;
          return this;
        }
        get _root() {
          return this._nodes[0];
        }
        get _currNode() {
          const ns = this._nodes;
          return ns[ns.length - 1];
        }
        set _currNode(node) {
          const ns = this._nodes;
          ns[ns.length - 1] = node;
        }
      }
      exports$12.CodeGen = CodeGen;
      function addNames(names2, from) {
        for (const n in from)
          names2[n] = (names2[n] || 0) + (from[n] || 0);
        return names2;
      }
      function addExprNames(names2, from) {
        return from instanceof code_1._CodeOrName ? addNames(names2, from.names) : names2;
      }
      function optimizeExpr(expr, names2, constants) {
        if (expr instanceof code_1.Name)
          return replaceName(expr);
        if (!canOptimize(expr))
          return expr;
        return new code_1._Code(expr._items.reduce((items2, c) => {
          if (c instanceof code_1.Name)
            c = replaceName(c);
          if (c instanceof code_1._Code)
            items2.push(...c._items);
          else
            items2.push(c);
          return items2;
        }, []));
        function replaceName(n) {
          const c = constants[n.str];
          if (c === void 0 || names2[n.str] !== 1)
            return n;
          delete names2[n.str];
          return c;
        }
        function canOptimize(e) {
          return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names2[c.str] === 1 && constants[c.str] !== void 0);
        }
      }
      function subtractNames(names2, from) {
        for (const n in from)
          names2[n] = (names2[n] || 0) - (from[n] || 0);
      }
      function not2(x) {
        return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`;
      }
      exports$12.not = not2;
      const andCode = mappend(exports$12.operators.AND);
      function and(...args) {
        return args.reduce(andCode);
      }
      exports$12.and = and;
      const orCode = mappend(exports$12.operators.OR);
      function or(...args) {
        return args.reduce(orCode);
      }
      exports$12.or = or;
      function mappend(op) {
        return (x, y) => x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y)}`;
      }
      function par(x) {
        return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`;
      }
    })(codegen);
    return codegen;
  }
  var util = {};
  var hasRequiredUtil;
  function requireUtil() {
    if (hasRequiredUtil) return util;
    hasRequiredUtil = 1;
    Object.defineProperty(util, "__esModule", { value: true });
    util.checkStrictMode = util.getErrorPath = util.Type = util.useFunc = util.setEvaluated = util.evaluatedPropsToName = util.mergeEvaluated = util.eachItem = util.unescapeJsonPointer = util.escapeJsonPointer = util.escapeFragment = util.unescapeFragment = util.schemaRefOrVal = util.schemaHasRulesButRef = util.schemaHasRules = util.checkUnknownRules = util.alwaysValidSchema = util.toHash = void 0;
    const codegen_1 = requireCodegen();
    const code_1 = requireCode$1();
    function toHash(arr) {
      const hash2 = {};
      for (const item of arr)
        hash2[item] = true;
      return hash2;
    }
    util.toHash = toHash;
    function alwaysValidSchema(it2, schema) {
      if (typeof schema == "boolean")
        return schema;
      if (Object.keys(schema).length === 0)
        return true;
      checkUnknownRules(it2, schema);
      return !schemaHasRules(schema, it2.self.RULES.all);
    }
    util.alwaysValidSchema = alwaysValidSchema;
    function checkUnknownRules(it2, schema = it2.schema) {
      const { opts, self: self2 } = it2;
      if (!opts.strictSchema)
        return;
      if (typeof schema === "boolean")
        return;
      const rules2 = self2.RULES.keywords;
      for (const key in schema) {
        if (!rules2[key])
          checkStrictMode(it2, `unknown keyword: "${key}"`);
      }
    }
    util.checkUnknownRules = checkUnknownRules;
    function schemaHasRules(schema, rules2) {
      if (typeof schema == "boolean")
        return !schema;
      for (const key in schema)
        if (rules2[key])
          return true;
      return false;
    }
    util.schemaHasRules = schemaHasRules;
    function schemaHasRulesButRef(schema, RULES) {
      if (typeof schema == "boolean")
        return !schema;
      for (const key in schema)
        if (key !== "$ref" && RULES.all[key])
          return true;
      return false;
    }
    util.schemaHasRulesButRef = schemaHasRulesButRef;
    function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword2, $data) {
      if (!$data) {
        if (typeof schema == "number" || typeof schema == "boolean")
          return schema;
        if (typeof schema == "string")
          return (0, codegen_1._)`${schema}`;
      }
      return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword2)}`;
    }
    util.schemaRefOrVal = schemaRefOrVal;
    function unescapeFragment(str) {
      return unescapeJsonPointer(decodeURIComponent(str));
    }
    util.unescapeFragment = unescapeFragment;
    function escapeFragment(str) {
      return encodeURIComponent(escapeJsonPointer(str));
    }
    util.escapeFragment = escapeFragment;
    function escapeJsonPointer(str) {
      if (typeof str == "number")
        return `${str}`;
      return str.replace(/~/g, "~0").replace(/\//g, "~1");
    }
    util.escapeJsonPointer = escapeJsonPointer;
    function unescapeJsonPointer(str) {
      return str.replace(/~1/g, "/").replace(/~0/g, "~");
    }
    util.unescapeJsonPointer = unescapeJsonPointer;
    function eachItem(xs, f) {
      if (Array.isArray(xs)) {
        for (const x of xs)
          f(x);
      } else {
        f(xs);
      }
    }
    util.eachItem = eachItem;
    function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues: mergeValues2, resultToName }) {
      return (gen, from, to, toName) => {
        const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues2(from, to);
        return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res;
      };
    }
    util.mergeEvaluated = {
      props: makeMergeEvaluated({
        mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => {
          gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`));
        }),
        mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => {
          if (from === true) {
            gen.assign(to, true);
          } else {
            gen.assign(to, (0, codegen_1._)`${to} || {}`);
            setEvaluated(gen, to, from);
          }
        }),
        mergeValues: (from, to) => from === true ? true : __spreadValues(__spreadValues({}, from), to),
        resultToName: evaluatedPropsToName
      }),
      items: makeMergeEvaluated({
        mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)),
        mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)),
        mergeValues: (from, to) => from === true ? true : Math.max(from, to),
        resultToName: (gen, items2) => gen.var("items", items2)
      })
    };
    function evaluatedPropsToName(gen, ps2) {
      if (ps2 === true)
        return gen.var("props", true);
      const props = gen.var("props", (0, codegen_1._)`{}`);
      if (ps2 !== void 0)
        setEvaluated(gen, props, ps2);
      return props;
    }
    util.evaluatedPropsToName = evaluatedPropsToName;
    function setEvaluated(gen, props, ps2) {
      Object.keys(ps2).forEach((p) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p)}`, true));
    }
    util.setEvaluated = setEvaluated;
    const snippets = {};
    function useFunc(gen, f) {
      return gen.scopeValue("func", {
        ref: f,
        code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code))
      });
    }
    util.useFunc = useFunc;
    var Type;
    (function(Type2) {
      Type2[Type2["Num"] = 0] = "Num";
      Type2[Type2["Str"] = 1] = "Str";
    })(Type || (util.Type = Type = {}));
    function getErrorPath(dataProp, dataPropType, jsPropertySyntax) {
      if (dataProp instanceof codegen_1.Name) {
        const isNumber = dataPropType === Type.Num;
        return jsPropertySyntax ? isNumber ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`;
      }
      return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp);
    }
    util.getErrorPath = getErrorPath;
    function checkStrictMode(it2, msg, mode = it2.opts.strictSchema) {
      if (!mode)
        return;
      msg = `strict mode: ${msg}`;
      if (mode === true)
        throw new Error(msg);
      it2.self.logger.warn(msg);
    }
    util.checkStrictMode = checkStrictMode;
    return util;
  }
  var names = {};
  var hasRequiredNames;
  function requireNames() {
    if (hasRequiredNames) return names;
    hasRequiredNames = 1;
    Object.defineProperty(names, "__esModule", { value: true });
    const codegen_1 = requireCodegen();
    const names$1 = {
      // validation function arguments
      data: new codegen_1.Name("data"),
      // data passed to validation function
      // args passed from referencing schema
      valCxt: new codegen_1.Name("valCxt"),
      // validation/data context - should not be used directly, it is destructured to the names below
      instancePath: new codegen_1.Name("instancePath"),
      parentData: new codegen_1.Name("parentData"),
      parentDataProperty: new codegen_1.Name("parentDataProperty"),
      rootData: new codegen_1.Name("rootData"),
      // root data - same as the data passed to the first/top validation function
      dynamicAnchors: new codegen_1.Name("dynamicAnchors"),
      // used to support recursiveRef and dynamicRef
      // function scoped variables
      vErrors: new codegen_1.Name("vErrors"),
      // null or array of validation errors
      errors: new codegen_1.Name("errors"),
      // counter of validation errors
      this: new codegen_1.Name("this"),
      // "globals"
      self: new codegen_1.Name("self"),
      scope: new codegen_1.Name("scope"),
      // JTD serialize/parse name for JSON string and position
      json: new codegen_1.Name("json"),
      jsonPos: new codegen_1.Name("jsonPos"),
      jsonLen: new codegen_1.Name("jsonLen"),
      jsonPart: new codegen_1.Name("jsonPart")
    };
    names.default = names$1;
    return names;
  }
  var hasRequiredErrors;
  function requireErrors() {
    if (hasRequiredErrors) return errors;
    hasRequiredErrors = 1;
    (function(exports$12) {
      Object.defineProperty(exports$12, "__esModule", { value: true });
      exports$12.extendErrors = exports$12.resetErrorsCount = exports$12.reportExtraError = exports$12.reportError = exports$12.keyword$DataError = exports$12.keywordError = void 0;
      const codegen_1 = requireCodegen();
      const util_1 = requireUtil();
      const names_1 = requireNames();
      exports$12.keywordError = {
        message: ({ keyword: keyword2 }) => (0, codegen_1.str)`must pass "${keyword2}" keyword validation`
      };
      exports$12.keyword$DataError = {
        message: ({ keyword: keyword2, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword2}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword2}" keyword is invalid ($data)`
      };
      function reportError2(cxt, error2 = exports$12.keywordError, errorPaths, overrideAllErrors) {
        const { it: it2 } = cxt;
        const { gen, compositeRule, allErrors } = it2;
        const errObj = errorObjectCode(cxt, error2, errorPaths);
        if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) {
          addError(gen, errObj);
        } else {
          returnErrors(it2, (0, codegen_1._)`[${errObj}]`);
        }
      }
      exports$12.reportError = reportError2;
      function reportExtraError(cxt, error2 = exports$12.keywordError, errorPaths) {
        const { it: it2 } = cxt;
        const { gen, compositeRule, allErrors } = it2;
        const errObj = errorObjectCode(cxt, error2, errorPaths);
        addError(gen, errObj);
        if (!(compositeRule || allErrors)) {
          returnErrors(it2, names_1.default.vErrors);
        }
      }
      exports$12.reportExtraError = reportExtraError;
      function resetErrorsCount(gen, errsCount) {
        gen.assign(names_1.default.errors, errsCount);
        gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null)));
      }
      exports$12.resetErrorsCount = resetErrorsCount;
      function extendErrors({ gen, keyword: keyword2, schemaValue, data, errsCount, it: it2 }) {
        if (errsCount === void 0)
          throw new Error("ajv implementation error");
        const err = gen.name("err");
        gen.forRange("i", errsCount, names_1.default.errors, (i2) => {
          gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i2}]`);
          gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it2.errorPath)));
          gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it2.errSchemaPath}/${keyword2}`);
          if (it2.opts.verbose) {
            gen.assign((0, codegen_1._)`${err}.schema`, schemaValue);
            gen.assign((0, codegen_1._)`${err}.data`, data);
          }
        });
      }
      exports$12.extendErrors = extendErrors;
      function addError(gen, errObj) {
        const err = gen.const("err", errObj);
        gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`);
        gen.code((0, codegen_1._)`${names_1.default.errors}++`);
      }
      function returnErrors(it2, errs) {
        const { gen, validateName, schemaEnv } = it2;
        if (schemaEnv.$async) {
          gen.throw((0, codegen_1._)`new ${it2.ValidationError}(${errs})`);
        } else {
          gen.assign((0, codegen_1._)`${validateName}.errors`, errs);
          gen.return(false);
        }
      }
      const E = {
        keyword: new codegen_1.Name("keyword"),
        schemaPath: new codegen_1.Name("schemaPath"),
        // also used in JTD errors
        params: new codegen_1.Name("params"),
        propertyName: new codegen_1.Name("propertyName"),
        message: new codegen_1.Name("message"),
        schema: new codegen_1.Name("schema"),
        parentSchema: new codegen_1.Name("parentSchema")
      };
      function errorObjectCode(cxt, error2, errorPaths) {
        const { createErrors } = cxt.it;
        if (createErrors === false)
          return (0, codegen_1._)`{}`;
        return errorObject(cxt, error2, errorPaths);
      }
      function errorObject(cxt, error2, errorPaths = {}) {
        const { gen, it: it2 } = cxt;
        const keyValues = [
          errorInstancePath(it2, errorPaths),
          errorSchemaPath(cxt, errorPaths)
        ];
        extraErrorProps(cxt, error2, keyValues);
        return gen.object(...keyValues);
      }
      function errorInstancePath({ errorPath }, { instancePath }) {
        const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath;
        return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)];
      }
      function errorSchemaPath({ keyword: keyword2, it: { errSchemaPath } }, { schemaPath, parentSchema }) {
        let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword2}`;
        if (schemaPath) {
          schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`;
        }
        return [E.schemaPath, schPath];
      }
      function extraErrorProps(cxt, { params, message }, keyValues) {
        const { keyword: keyword2, data, schemaValue, it: it2 } = cxt;
        const { opts, propertyName, topSchemaRef, schemaPath } = it2;
        keyValues.push([E.keyword, keyword2], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]);
        if (opts.messages) {
          keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]);
        }
        if (opts.verbose) {
          keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]);
        }
        if (propertyName)
          keyValues.push([E.propertyName, propertyName]);
      }
    })(errors);
    return errors;
  }
  var hasRequiredBoolSchema;
  function requireBoolSchema() {
    if (hasRequiredBoolSchema) return boolSchema;
    hasRequiredBoolSchema = 1;
    Object.defineProperty(boolSchema, "__esModule", { value: true });
    boolSchema.boolOrEmptySchema = boolSchema.topBoolOrEmptySchema = void 0;
    const errors_1 = requireErrors();
    const codegen_1 = requireCodegen();
    const names_1 = requireNames();
    const boolError = {
      message: "boolean schema is false"
    };
    function topBoolOrEmptySchema(it2) {
      const { gen, schema, validateName } = it2;
      if (schema === false) {
        falseSchemaError(it2, false);
      } else if (typeof schema == "object" && schema.$async === true) {
        gen.return(names_1.default.data);
      } else {
        gen.assign((0, codegen_1._)`${validateName}.errors`, null);
        gen.return(true);
      }
    }
    boolSchema.topBoolOrEmptySchema = topBoolOrEmptySchema;
    function boolOrEmptySchema(it2, valid) {
      const { gen, schema } = it2;
      if (schema === false) {
        gen.var(valid, false);
        falseSchemaError(it2);
      } else {
        gen.var(valid, true);
      }
    }
    boolSchema.boolOrEmptySchema = boolOrEmptySchema;
    function falseSchemaError(it2, overrideAllErrors) {
      const { gen, data } = it2;
      const cxt = {
        gen,
        keyword: "false schema",
        data,
        schema: false,
        schemaCode: false,
        schemaValue: false,
        params: {},
        it: it2
      };
      (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors);
    }
    return boolSchema;
  }
  var dataType = {};
  var rules = {};
  var hasRequiredRules;
  function requireRules() {
    if (hasRequiredRules) return rules;
    hasRequiredRules = 1;
    Object.defineProperty(rules, "__esModule", { value: true });
    rules.getRules = rules.isJSONType = void 0;
    const _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"];
    const jsonTypes = new Set(_jsonTypes);
    function isJSONType(x) {
      return typeof x == "string" && jsonTypes.has(x);
    }
    rules.isJSONType = isJSONType;
    function getRules() {
      const groups = {
        number: { type: "number", rules: [] },
        string: { type: "string", rules: [] },
        array: { type: "array", rules: [] },
        object: { type: "object", rules: [] }
      };
      return {
        types: __spreadProps(__spreadValues({}, groups), { integer: true, boolean: true, null: true }),
        rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object],
        post: { rules: [] },
        all: {},
        keywords: {}
      };
    }
    rules.getRules = getRules;
    return rules;
  }
  var applicability = {};
  var hasRequiredApplicability;
  function requireApplicability() {
    if (hasRequiredApplicability) return applicability;
    hasRequiredApplicability = 1;
    Object.defineProperty(applicability, "__esModule", { value: true });
    applicability.shouldUseRule = applicability.shouldUseGroup = applicability.schemaHasRulesForType = void 0;
    function schemaHasRulesForType({ schema, self: self2 }, type2) {
      const group = self2.RULES.types[type2];
      return group && group !== true && shouldUseGroup(schema, group);
    }
    applicability.schemaHasRulesForType = schemaHasRulesForType;
    function shouldUseGroup(schema, group) {
      return group.rules.some((rule) => shouldUseRule(schema, rule));
    }
    applicability.shouldUseGroup = shouldUseGroup;
    function shouldUseRule(schema, rule) {
      var _a3;
      return schema[rule.keyword] !== void 0 || ((_a3 = rule.definition.implements) === null || _a3 === void 0 ? void 0 : _a3.some((kwd) => schema[kwd] !== void 0));
    }
    applicability.shouldUseRule = shouldUseRule;
    return applicability;
  }
  var hasRequiredDataType;
  function requireDataType() {
    if (hasRequiredDataType) return dataType;
    hasRequiredDataType = 1;
    Object.defineProperty(dataType, "__esModule", { value: true });
    dataType.reportTypeError = dataType.checkDataTypes = dataType.checkDataType = dataType.coerceAndCheckDataType = dataType.getJSONTypes = dataType.getSchemaTypes = dataType.DataType = void 0;
    const rules_1 = requireRules();
    const applicability_1 = requireApplicability();
    const errors_1 = requireErrors();
    const codegen_1 = requireCodegen();
    const util_1 = requireUtil();
    var DataType;
    (function(DataType2) {
      DataType2[DataType2["Correct"] = 0] = "Correct";
      DataType2[DataType2["Wrong"] = 1] = "Wrong";
    })(DataType || (dataType.DataType = DataType = {}));
    function getSchemaTypes(schema) {
      const types2 = getJSONTypes(schema.type);
      const hasNull = types2.includes("null");
      if (hasNull) {
        if (schema.nullable === false)
          throw new Error("type: null contradicts nullable: false");
      } else {
        if (!types2.length && schema.nullable !== void 0) {
          throw new Error('"nullable" cannot be used without "type"');
        }
        if (schema.nullable === true)
          types2.push("null");
      }
      return types2;
    }
    dataType.getSchemaTypes = getSchemaTypes;
    function getJSONTypes(ts) {
      const types2 = Array.isArray(ts) ? ts : ts ? [ts] : [];
      if (types2.every(rules_1.isJSONType))
        return types2;
      throw new Error("type must be JSONType or JSONType[]: " + types2.join(","));
    }
    dataType.getJSONTypes = getJSONTypes;
    function coerceAndCheckDataType(it2, types2) {
      const { gen, data, opts } = it2;
      const coerceTo = coerceToTypes(types2, opts.coerceTypes);
      const checkTypes = types2.length > 0 && !(coerceTo.length === 0 && types2.length === 1 && (0, applicability_1.schemaHasRulesForType)(it2, types2[0]));
      if (checkTypes) {
        const wrongType = checkDataTypes(types2, data, opts.strictNumbers, DataType.Wrong);
        gen.if(wrongType, () => {
          if (coerceTo.length)
            coerceData(it2, types2, coerceTo);
          else
            reportTypeError(it2);
        });
      }
      return checkTypes;
    }
    dataType.coerceAndCheckDataType = coerceAndCheckDataType;
    const COERCIBLE = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "null"]);
    function coerceToTypes(types2, coerceTypes) {
      return coerceTypes ? types2.filter((t) => COERCIBLE.has(t) || coerceTypes === "array" && t === "array") : [];
    }
    function coerceData(it2, types2, coerceTo) {
      const { gen, data, opts } = it2;
      const dataType2 = gen.let("dataType", (0, codegen_1._)`typeof ${data}`);
      const coerced = gen.let("coerced", (0, codegen_1._)`undefined`);
      if (opts.coerceTypes === "array") {
        gen.if((0, codegen_1._)`${dataType2} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType2, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types2, data, opts.strictNumbers), () => gen.assign(coerced, data)));
      }
      gen.if((0, codegen_1._)`${coerced} !== undefined`);
      for (const t of coerceTo) {
        if (COERCIBLE.has(t) || t === "array" && opts.coerceTypes === "array") {
          coerceSpecificType(t);
        }
      }
      gen.else();
      reportTypeError(it2);
      gen.endIf();
      gen.if((0, codegen_1._)`${coerced} !== undefined`, () => {
        gen.assign(data, coerced);
        assignParentData(it2, coerced);
      });
      function coerceSpecificType(t) {
        switch (t) {
          case "string":
            gen.elseIf((0, codegen_1._)`${dataType2} == "number" || ${dataType2} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`);
            return;
          case "number":
            gen.elseIf((0, codegen_1._)`${dataType2} == "boolean" || ${data} === null
              || (${dataType2} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`);
            return;
          case "integer":
            gen.elseIf((0, codegen_1._)`${dataType2} === "boolean" || ${data} === null
              || (${dataType2} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`);
            return;
          case "boolean":
            gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true);
            return;
          case "null":
            gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`);
            gen.assign(coerced, null);
            return;
          case "array":
            gen.elseIf((0, codegen_1._)`${dataType2} === "string" || ${dataType2} === "number"
              || ${dataType2} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`);
        }
      }
    }
    function assignParentData({ gen, parentData, parentDataProperty }, expr) {
      gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr));
    }
    function checkDataType(dataType2, data, strictNums, correct = DataType.Correct) {
      const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ;
      let cond;
      switch (dataType2) {
        case "null":
          return (0, codegen_1._)`${data} ${EQ} null`;
        case "array":
          cond = (0, codegen_1._)`Array.isArray(${data})`;
          break;
        case "object":
          cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`;
          break;
        case "integer":
          cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`);
          break;
        case "number":
          cond = numCond();
          break;
        default:
          return (0, codegen_1._)`typeof ${data} ${EQ} ${dataType2}`;
      }
      return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond);
      function numCond(_cond = codegen_1.nil) {
        return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil);
      }
    }
    dataType.checkDataType = checkDataType;
    function checkDataTypes(dataTypes, data, strictNums, correct) {
      if (dataTypes.length === 1) {
        return checkDataType(dataTypes[0], data, strictNums, correct);
      }
      let cond;
      const types2 = (0, util_1.toHash)(dataTypes);
      if (types2.array && types2.object) {
        const notObj = (0, codegen_1._)`typeof ${data} != "object"`;
        cond = types2.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`;
        delete types2.null;
        delete types2.array;
        delete types2.object;
      } else {
        cond = codegen_1.nil;
      }
      if (types2.number)
        delete types2.integer;
      for (const t in types2)
        cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct));
      return cond;
    }
    dataType.checkDataTypes = checkDataTypes;
    const typeError = {
      message: ({ schema }) => `must be ${schema}`,
      params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}`
    };
    function reportTypeError(it2) {
      const cxt = getTypeErrorContext(it2);
      (0, errors_1.reportError)(cxt, typeError);
    }
    dataType.reportTypeError = reportTypeError;
    function getTypeErrorContext(it2) {
      const { gen, data, schema } = it2;
      const schemaCode = (0, util_1.schemaRefOrVal)(it2, schema, "type");
      return {
        gen,
        keyword: "type",
        data,
        schema: schema.type,
        schemaCode,
        schemaValue: schemaCode,
        parentSchema: schema,
        params: {},
        it: it2
      };
    }
    return dataType;
  }
  var defaults = {};
  var hasRequiredDefaults;
  function requireDefaults() {
    if (hasRequiredDefaults) return defaults;
    hasRequiredDefaults = 1;
    Object.defineProperty(defaults, "__esModule", { value: true });
    defaults.assignDefaults = void 0;
    const codegen_1 = requireCodegen();
    const util_1 = requireUtil();
    function assignDefaults(it2, ty) {
      const { properties: properties2, items: items2 } = it2.schema;
      if (ty === "object" && properties2) {
        for (const key in properties2) {
          assignDefault(it2, key, properties2[key].default);
        }
      } else if (ty === "array" && Array.isArray(items2)) {
        items2.forEach((sch, i2) => assignDefault(it2, i2, sch.default));
      }
    }
    defaults.assignDefaults = assignDefaults;
    function assignDefault(it2, prop, defaultValue) {
      const { gen, compositeRule, data, opts } = it2;
      if (defaultValue === void 0)
        return;
      const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`;
      if (compositeRule) {
        (0, util_1.checkStrictMode)(it2, `default is ignored for: ${childData}`);
        return;
      }
      let condition = (0, codegen_1._)`${childData} === undefined`;
      if (opts.useDefaults === "empty") {
        condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`;
      }
      gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`);
    }
    return defaults;
  }
  var keyword = {};
  var code$1 = {};
  var hasRequiredCode;
  function requireCode() {
    if (hasRequiredCode) return code$1;
    hasRequiredCode = 1;
    Object.defineProperty(code$1, "__esModule", { value: true });
    code$1.validateUnion = code$1.validateArray = code$1.usePattern = code$1.callValidateCode = code$1.schemaProperties = code$1.allSchemaProperties = code$1.noPropertyInData = code$1.propertyInData = code$1.isOwnProperty = code$1.hasPropFunc = code$1.reportMissingProp = code$1.checkMissingProp = code$1.checkReportMissingProp = void 0;
    const codegen_1 = requireCodegen();
    const util_1 = requireUtil();
    const names_1 = requireNames();
    const util_2 = requireUtil();
    function checkReportMissingProp(cxt, prop) {
      const { gen, data, it: it2 } = cxt;
      gen.if(noPropertyInData(gen, data, prop, it2.opts.ownProperties), () => {
        cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true);
        cxt.error();
      });
    }
    code$1.checkReportMissingProp = checkReportMissingProp;
    function checkMissingProp({ gen, data, it: { opts } }, properties2, missing) {
      return (0, codegen_1.or)(...properties2.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`)));
    }
    code$1.checkMissingProp = checkMissingProp;
    function reportMissingProp(cxt, missing) {
      cxt.setParams({ missingProperty: missing }, true);
      cxt.error();
    }
    code$1.reportMissingProp = reportMissingProp;
    function hasPropFunc(gen) {
      return gen.scopeValue("func", {
        // eslint-disable-next-line @typescript-eslint/unbound-method
        ref: Object.prototype.hasOwnProperty,
        code: (0, codegen_1._)`Object.prototype.hasOwnProperty`
      });
    }
    code$1.hasPropFunc = hasPropFunc;
    function isOwnProperty(gen, data, property) {
      return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`;
    }
    code$1.isOwnProperty = isOwnProperty;
    function propertyInData(gen, data, property, ownProperties) {
      const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`;
      return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond;
    }
    code$1.propertyInData = propertyInData;
    function noPropertyInData(gen, data, property, ownProperties) {
      const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`;
      return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond;
    }
    code$1.noPropertyInData = noPropertyInData;
    function allSchemaProperties(schemaMap) {
      return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : [];
    }
    code$1.allSchemaProperties = allSchemaProperties;
    function schemaProperties(it2, schemaMap) {
      return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it2, schemaMap[p]));
    }
    code$1.schemaProperties = schemaProperties;
    function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it: it2 }, func, context, passSchema) {
      const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data;
      const valCxt = [
        [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)],
        [names_1.default.parentData, it2.parentData],
        [names_1.default.parentDataProperty, it2.parentDataProperty],
        [names_1.default.rootData, names_1.default.rootData]
      ];
      if (it2.opts.dynamicRef)
        valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]);
      const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`;
      return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`;
    }
    code$1.callValidateCode = callValidateCode;
    const newRegExp = (0, codegen_1._)`new RegExp`;
    function usePattern({ gen, it: { opts } }, pattern2) {
      const u = opts.unicodeRegExp ? "u" : "";
      const { regExp } = opts.code;
      const rx = regExp(pattern2, u);
      return gen.scopeValue("pattern", {
        key: rx.toString(),
        ref: rx,
        code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern2}, ${u})`
      });
    }
    code$1.usePattern = usePattern;
    function validateArray(cxt) {
      const { gen, data, keyword: keyword2, it: it2 } = cxt;
      const valid = gen.name("valid");
      if (it2.allErrors) {
        const validArr = gen.let("valid", true);
        validateItems(() => gen.assign(validArr, false));
        return validArr;
      }
      gen.var(valid, true);
      validateItems(() => gen.break());
      return valid;
      function validateItems(notValid) {
        const len2 = gen.const("len", (0, codegen_1._)`${data}.length`);
        gen.forRange("i", 0, len2, (i2) => {
          cxt.subschema({
            keyword: keyword2,
            dataProp: i2,
            dataPropType: util_1.Type.Num
          }, valid);
          gen.if((0, codegen_1.not)(valid), notValid);
        });
      }
    }
    code$1.validateArray = validateArray;
    function validateUnion(cxt) {
      const { gen, schema, keyword: keyword2, it: it2 } = cxt;
      if (!Array.isArray(schema))
        throw new Error("ajv implementation error");
      const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it2, sch));
      if (alwaysValid && !it2.opts.unevaluated)
        return;
      const valid = gen.let("valid", false);
      const schValid = gen.name("_valid");
      gen.block(() => schema.forEach((_sch, i2) => {
        const schCxt = cxt.subschema({
          keyword: keyword2,
          schemaProp: i2,
          compositeRule: true
        }, schValid);
        gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`);
        const merged = cxt.mergeValidEvaluated(schCxt, schValid);
        if (!merged)
          gen.if((0, codegen_1.not)(valid));
      }));
      cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
    }
    code$1.validateUnion = validateUnion;
    return code$1;
  }
  var hasRequiredKeyword;
  function requireKeyword() {
    if (hasRequiredKeyword) return keyword;
    hasRequiredKeyword = 1;
    Object.defineProperty(keyword, "__esModule", { value: true });
    keyword.validateKeywordUsage = keyword.validSchemaType = keyword.funcKeywordCode = keyword.macroKeywordCode = void 0;
    const codegen_1 = requireCodegen();
    const names_1 = requireNames();
    const code_1 = requireCode();
    const errors_1 = requireErrors();
    function macroKeywordCode(cxt, def) {
      const { gen, keyword: keyword2, schema, parentSchema, it: it2 } = cxt;
      const macroSchema = def.macro.call(it2.self, schema, parentSchema, it2);
      const schemaRef = useKeyword(gen, keyword2, macroSchema);
      if (it2.opts.validateSchema !== false)
        it2.self.validateSchema(macroSchema, true);
      const valid = gen.name("valid");
      cxt.subschema({
        schema: macroSchema,
        schemaPath: codegen_1.nil,
        errSchemaPath: `${it2.errSchemaPath}/${keyword2}`,
        topSchemaRef: schemaRef,
        compositeRule: true
      }, valid);
      cxt.pass(valid, () => cxt.error(true));
    }
    keyword.macroKeywordCode = macroKeywordCode;
    function funcKeywordCode(cxt, def) {
      var _a3;
      const { gen, keyword: keyword2, schema, parentSchema, $data, it: it2 } = cxt;
      checkAsyncKeyword(it2, def);
      const validate2 = !$data && def.compile ? def.compile.call(it2.self, schema, parentSchema, it2) : def.validate;
      const validateRef = useKeyword(gen, keyword2, validate2);
      const valid = gen.let("valid");
      cxt.block$data(valid, validateKeyword);
      cxt.ok((_a3 = def.valid) !== null && _a3 !== void 0 ? _a3 : valid);
      function validateKeyword() {
        if (def.errors === false) {
          assignValid();
          if (def.modifying)
            modifyData(cxt);
          reportErrs(() => cxt.error());
        } else {
          const ruleErrs = def.async ? validateAsync() : validateSync();
          if (def.modifying)
            modifyData(cxt);
          reportErrs(() => addErrs(cxt, ruleErrs));
        }
      }
      function validateAsync() {
        const ruleErrs = gen.let("ruleErrs", null);
        gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it2.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e)));
        return ruleErrs;
      }
      function validateSync() {
        const validateErrs = (0, codegen_1._)`${validateRef}.errors`;
        gen.assign(validateErrs, null);
        assignValid(codegen_1.nil);
        return validateErrs;
      }
      function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) {
        const passCxt = it2.opts.passContext ? names_1.default.this : names_1.default.self;
        const passSchema = !("compile" in def && !$data || def.schema === false);
        gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying);
      }
      function reportErrs(errors2) {
        var _a4;
        gen.if((0, codegen_1.not)((_a4 = def.valid) !== null && _a4 !== void 0 ? _a4 : valid), errors2);
      }
    }
    keyword.funcKeywordCode = funcKeywordCode;
    function modifyData(cxt) {
      const { gen, data, it: it2 } = cxt;
      gen.if(it2.parentData, () => gen.assign(data, (0, codegen_1._)`${it2.parentData}[${it2.parentDataProperty}]`));
    }
    function addErrs(cxt, errs) {
      const { gen } = cxt;
      gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => {
        gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`);
        (0, errors_1.extendErrors)(cxt);
      }, () => cxt.error());
    }
    function checkAsyncKeyword({ schemaEnv }, def) {
      if (def.async && !schemaEnv.$async)
        throw new Error("async keyword in sync schema");
    }
    function useKeyword(gen, keyword2, result2) {
      if (result2 === void 0)
        throw new Error(`keyword "${keyword2}" failed to compile`);
      return gen.scopeValue("keyword", typeof result2 == "function" ? { ref: result2 } : { ref: result2, code: (0, codegen_1.stringify)(result2) });
    }
    function validSchemaType(schema, schemaType, allowUndefined = false) {
      return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined");
    }
    keyword.validSchemaType = validSchemaType;
    function validateKeywordUsage({ schema, opts, self: self2, errSchemaPath }, def, keyword2) {
      if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword2) : def.keyword !== keyword2) {
        throw new Error("ajv implementation error");
      }
      const deps = def.dependencies;
      if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {
        throw new Error(`parent schema must have dependencies of ${keyword2}: ${deps.join(",")}`);
      }
      if (def.validateSchema) {
        const valid = def.validateSchema(schema[keyword2]);
        if (!valid) {
          const msg = `keyword "${keyword2}" value is invalid at path "${errSchemaPath}": ` + self2.errorsText(def.validateSchema.errors);
          if (opts.validateSchema === "log")
            self2.logger.error(msg);
          else
            throw new Error(msg);
        }
      }
    }
    keyword.validateKeywordUsage = validateKeywordUsage;
    return keyword;
  }
  var subschema = {};
  var hasRequiredSubschema;
  function requireSubschema() {
    if (hasRequiredSubschema) return subschema;
    hasRequiredSubschema = 1;
    Object.defineProperty(subschema, "__esModule", { value: true });
    subschema.extendSubschemaMode = subschema.extendSubschemaData = subschema.getSubschema = void 0;
    const codegen_1 = requireCodegen();
    const util_1 = requireUtil();
    function getSubschema(it2, { keyword: keyword2, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) {
      if (keyword2 !== void 0 && schema !== void 0) {
        throw new Error('both "keyword" and "schema" passed, only one allowed');
      }
      if (keyword2 !== void 0) {
        const sch = it2.schema[keyword2];
        return schemaProp === void 0 ? {
          schema: sch,
          schemaPath: (0, codegen_1._)`${it2.schemaPath}${(0, codegen_1.getProperty)(keyword2)}`,
          errSchemaPath: `${it2.errSchemaPath}/${keyword2}`
        } : {
          schema: sch[schemaProp],
          schemaPath: (0, codegen_1._)`${it2.schemaPath}${(0, codegen_1.getProperty)(keyword2)}${(0, codegen_1.getProperty)(schemaProp)}`,
          errSchemaPath: `${it2.errSchemaPath}/${keyword2}/${(0, util_1.escapeFragment)(schemaProp)}`
        };
      }
      if (schema !== void 0) {
        if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) {
          throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');
        }
        return {
          schema,
          schemaPath,
          topSchemaRef,
          errSchemaPath
        };
      }
      throw new Error('either "keyword" or "schema" must be passed');
    }
    subschema.getSubschema = getSubschema;
    function extendSubschemaData(subschema2, it2, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) {
      if (data !== void 0 && dataProp !== void 0) {
        throw new Error('both "data" and "dataProp" passed, only one allowed');
      }
      const { gen } = it2;
      if (dataProp !== void 0) {
        const { errorPath, dataPathArr, opts } = it2;
        const nextData = gen.let("data", (0, codegen_1._)`${it2.data}${(0, codegen_1.getProperty)(dataProp)}`, true);
        dataContextProps(nextData);
        subschema2.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`;
        subschema2.parentDataProperty = (0, codegen_1._)`${dataProp}`;
        subschema2.dataPathArr = [...dataPathArr, subschema2.parentDataProperty];
      }
      if (data !== void 0) {
        const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true);
        dataContextProps(nextData);
        if (propertyName !== void 0)
          subschema2.propertyName = propertyName;
      }
      if (dataTypes)
        subschema2.dataTypes = dataTypes;
      function dataContextProps(_nextData) {
        subschema2.data = _nextData;
        subschema2.dataLevel = it2.dataLevel + 1;
        subschema2.dataTypes = [];
        it2.definedProperties = /* @__PURE__ */ new Set();
        subschema2.parentData = it2.data;
        subschema2.dataNames = [...it2.dataNames, _nextData];
      }
    }
    subschema.extendSubschemaData = extendSubschemaData;
    function extendSubschemaMode(subschema2, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) {
      if (compositeRule !== void 0)
        subschema2.compositeRule = compositeRule;
      if (createErrors !== void 0)
        subschema2.createErrors = createErrors;
      if (allErrors !== void 0)
        subschema2.allErrors = allErrors;
      subschema2.jtdDiscriminator = jtdDiscriminator;
      subschema2.jtdMetadata = jtdMetadata;
    }
    subschema.extendSubschemaMode = extendSubschemaMode;
    return subschema;
  }
  var resolve = {};
  var fastDeepEqual;
  var hasRequiredFastDeepEqual;
  function requireFastDeepEqual() {
    if (hasRequiredFastDeepEqual) return fastDeepEqual;
    hasRequiredFastDeepEqual = 1;
    fastDeepEqual = function equal2(a, b) {
      if (a === b) return true;
      if (a && b && typeof a == "object" && typeof b == "object") {
        if (a.constructor !== b.constructor) return false;
        var length, i2, keys;
        if (Array.isArray(a)) {
          length = a.length;
          if (length != b.length) return false;
          for (i2 = length; i2-- !== 0; )
            if (!equal2(a[i2], b[i2])) return false;
          return true;
        }
        if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
        if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
        if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
        keys = Object.keys(a);
        length = keys.length;
        if (length !== Object.keys(b).length) return false;
        for (i2 = length; i2-- !== 0; )
          if (!Object.prototype.hasOwnProperty.call(b, keys[i2])) return false;
        for (i2 = length; i2-- !== 0; ) {
          var key = keys[i2];
          if (!equal2(a[key], b[key])) return false;
        }
        return true;
      }
      return a !== a && b !== b;
    };
    return fastDeepEqual;
  }
  var jsonSchemaTraverse = { exports: {} };
  var hasRequiredJsonSchemaTraverse;
  function requireJsonSchemaTraverse() {
    if (hasRequiredJsonSchemaTraverse) return jsonSchemaTraverse.exports;
    hasRequiredJsonSchemaTraverse = 1;
    var traverse = jsonSchemaTraverse.exports = function(schema, opts, cb) {
      if (typeof opts == "function") {
        cb = opts;
        opts = {};
      }
      cb = opts.cb || cb;
      var pre = typeof cb == "function" ? cb : cb.pre || function() {
      };
      var post = cb.post || function() {
      };
      _traverse(opts, pre, post, schema, "", schema);
    };
    traverse.keywords = {
      additionalItems: true,
      items: true,
      contains: true,
      additionalProperties: true,
      propertyNames: true,
      not: true,
      if: true,
      then: true,
      else: true
    };
    traverse.arrayKeywords = {
      items: true,
      allOf: true,
      anyOf: true,
      oneOf: true
    };
    traverse.propsKeywords = {
      $defs: true,
      definitions: true,
      properties: true,
      patternProperties: true,
      dependencies: true
    };
    traverse.skipKeywords = {
      default: true,
      enum: true,
      const: true,
      required: true,
      maximum: true,
      minimum: true,
      exclusiveMaximum: true,
      exclusiveMinimum: true,
      multipleOf: true,
      maxLength: true,
      minLength: true,
      pattern: true,
      format: true,
      maxItems: true,
      minItems: true,
      uniqueItems: true,
      maxProperties: true,
      minProperties: true
    };
    function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
      if (schema && typeof schema == "object" && !Array.isArray(schema)) {
        pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
        for (var key in schema) {
          var sch = schema[key];
          if (Array.isArray(sch)) {
            if (key in traverse.arrayKeywords) {
              for (var i2 = 0; i2 < sch.length; i2++)
                _traverse(opts, pre, post, sch[i2], jsonPtr + "/" + key + "/" + i2, rootSchema, jsonPtr, key, schema, i2);
            }
          } else if (key in traverse.propsKeywords) {
            if (sch && typeof sch == "object") {
              for (var prop in sch)
                _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
            }
          } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) {
            _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema);
          }
        }
        post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
      }
    }
    function escapeJsonPtr(str) {
      return str.replace(/~/g, "~0").replace(/\//g, "~1");
    }
    return jsonSchemaTraverse.exports;
  }
  var hasRequiredResolve;
  function requireResolve() {
    if (hasRequiredResolve) return resolve;
    hasRequiredResolve = 1;
    Object.defineProperty(resolve, "__esModule", { value: true });
    resolve.getSchemaRefs = resolve.resolveUrl = resolve.normalizeId = resolve._getFullPath = resolve.getFullPath = resolve.inlineRef = void 0;
    const util_1 = requireUtil();
    const equal2 = requireFastDeepEqual();
    const traverse = requireJsonSchemaTraverse();
    const SIMPLE_INLINED = /* @__PURE__ */ new Set([
      "type",
      "format",
      "pattern",
      "maxLength",
      "minLength",
      "maxProperties",
      "minProperties",
      "maxItems",
      "minItems",
      "maximum",
      "minimum",
      "uniqueItems",
      "multipleOf",
      "required",
      "enum",
      "const"
    ]);
    function inlineRef(schema, limit2 = true) {
      if (typeof schema == "boolean")
        return true;
      if (limit2 === true)
        return !hasRef(schema);
      if (!limit2)
        return false;
      return countKeys(schema) <= limit2;
    }
    resolve.inlineRef = inlineRef;
    const REF_KEYWORDS = /* @__PURE__ */ new Set([
      "$ref",
      "$recursiveRef",
      "$recursiveAnchor",
      "$dynamicRef",
      "$dynamicAnchor"
    ]);
    function hasRef(schema) {
      for (const key in schema) {
        if (REF_KEYWORDS.has(key))
          return true;
        const sch = schema[key];
        if (Array.isArray(sch) && sch.some(hasRef))
          return true;
        if (typeof sch == "object" && hasRef(sch))
          return true;
      }
      return false;
    }
    function countKeys(schema) {
      let count = 0;
      for (const key in schema) {
        if (key === "$ref")
          return Infinity;
        count++;
        if (SIMPLE_INLINED.has(key))
          continue;
        if (typeof schema[key] == "object") {
          (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch));
        }
        if (count === Infinity)
          return Infinity;
      }
      return count;
    }
    function getFullPath(resolver, id2 = "", normalize) {
      if (normalize !== false)
        id2 = normalizeId(id2);
      const p = resolver.parse(id2);
      return _getFullPath(resolver, p);
    }
    resolve.getFullPath = getFullPath;
    function _getFullPath(resolver, p) {
      const serialized = resolver.serialize(p);
      return serialized.split("#")[0] + "#";
    }
    resolve._getFullPath = _getFullPath;
    const TRAILING_SLASH_HASH = /#\/?$/;
    function normalizeId(id2) {
      return id2 ? id2.replace(TRAILING_SLASH_HASH, "") : "";
    }
    resolve.normalizeId = normalizeId;
    function resolveUrl(resolver, baseId, id2) {
      id2 = normalizeId(id2);
      return resolver.resolve(baseId, id2);
    }
    resolve.resolveUrl = resolveUrl;
    const ANCHOR = /^[a-z_][-a-z0-9._]*$/i;
    function getSchemaRefs(schema, baseId) {
      if (typeof schema == "boolean")
        return {};
      const { schemaId, uriResolver } = this.opts;
      const schId = normalizeId(schema[schemaId] || baseId);
      const baseIds = { "": schId };
      const pathPrefix = getFullPath(uriResolver, schId, false);
      const localRefs = {};
      const schemaRefs = /* @__PURE__ */ new Set();
      traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => {
        if (parentJsonPtr === void 0)
          return;
        const fullPath = pathPrefix + jsonPtr;
        let innerBaseId = baseIds[parentJsonPtr];
        if (typeof sch[schemaId] == "string")
          innerBaseId = addRef.call(this, sch[schemaId]);
        addAnchor.call(this, sch.$anchor);
        addAnchor.call(this, sch.$dynamicAnchor);
        baseIds[jsonPtr] = innerBaseId;
        function addRef(ref2) {
          const _resolve = this.opts.uriResolver.resolve;
          ref2 = normalizeId(innerBaseId ? _resolve(innerBaseId, ref2) : ref2);
          if (schemaRefs.has(ref2))
            throw ambiguos(ref2);
          schemaRefs.add(ref2);
          let schOrRef = this.refs[ref2];
          if (typeof schOrRef == "string")
            schOrRef = this.refs[schOrRef];
          if (typeof schOrRef == "object") {
            checkAmbiguosRef(sch, schOrRef.schema, ref2);
          } else if (ref2 !== normalizeId(fullPath)) {
            if (ref2[0] === "#") {
              checkAmbiguosRef(sch, localRefs[ref2], ref2);
              localRefs[ref2] = sch;
            } else {
              this.refs[ref2] = fullPath;
            }
          }
          return ref2;
        }
        function addAnchor(anchor) {
          if (typeof anchor == "string") {
            if (!ANCHOR.test(anchor))
              throw new Error(`invalid anchor "${anchor}"`);
            addRef.call(this, `#${anchor}`);
          }
        }
      });
      return localRefs;
      function checkAmbiguosRef(sch1, sch2, ref2) {
        if (sch2 !== void 0 && !equal2(sch1, sch2))
          throw ambiguos(ref2);
      }
      function ambiguos(ref2) {
        return new Error(`reference "${ref2}" resolves to more than one schema`);
      }
    }
    resolve.getSchemaRefs = getSchemaRefs;
    return resolve;
  }
  var hasRequiredValidate;
  function requireValidate() {
    if (hasRequiredValidate) return validate;
    hasRequiredValidate = 1;
    Object.defineProperty(validate, "__esModule", { value: true });
    validate.getData = validate.KeywordCxt = validate.validateFunctionCode = void 0;
    const boolSchema_1 = requireBoolSchema();
    const dataType_1 = requireDataType();
    const applicability_1 = requireApplicability();
    const dataType_2 = requireDataType();
    const defaults_1 = requireDefaults();
    const keyword_1 = requireKeyword();
    const subschema_1 = requireSubschema();
    const codegen_1 = requireCodegen();
    const names_1 = requireNames();
    const resolve_1 = requireResolve();
    const util_1 = requireUtil();
    const errors_1 = requireErrors();
    function validateFunctionCode(it2) {
      if (isSchemaObj(it2)) {
        checkKeywords(it2);
        if (schemaCxtHasRules(it2)) {
          topSchemaObjCode(it2);
          return;
        }
      }
      validateFunction(it2, () => (0, boolSchema_1.topBoolOrEmptySchema)(it2));
    }
    validate.validateFunctionCode = validateFunctionCode;
    function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) {
      if (opts.code.es5) {
        gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => {
          gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`);
          destructureValCxtES5(gen, opts);
          gen.code(body);
        });
      } else {
        gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body));
      }
    }
    function destructureValCxt(opts) {
      return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`;
    }
    function destructureValCxtES5(gen, opts) {
      gen.if(names_1.default.valCxt, () => {
        gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`);
        gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`);
        gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`);
        gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`);
        if (opts.dynamicRef)
          gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`);
      }, () => {
        gen.var(names_1.default.instancePath, (0, codegen_1._)`""`);
        gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`);
        gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`);
        gen.var(names_1.default.rootData, names_1.default.data);
        if (opts.dynamicRef)
          gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`);
      });
    }
    function topSchemaObjCode(it2) {
      const { schema, opts, gen } = it2;
      validateFunction(it2, () => {
        if (opts.$comment && schema.$comment)
          commentKeyword(it2);
        checkNoDefault(it2);
        gen.let(names_1.default.vErrors, null);
        gen.let(names_1.default.errors, 0);
        if (opts.unevaluated)
          resetEvaluated(it2);
        typeAndKeywords(it2);
        returnResults(it2);
      });
      return;
    }
    function resetEvaluated(it2) {
      const { gen, validateName } = it2;
      it2.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`);
      gen.if((0, codegen_1._)`${it2.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it2.evaluated}.props`, (0, codegen_1._)`undefined`));
      gen.if((0, codegen_1._)`${it2.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it2.evaluated}.items`, (0, codegen_1._)`undefined`));
    }
    function funcSourceUrl(schema, opts) {
      const schId = typeof schema == "object" && schema[opts.schemaId];
      return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil;
    }
    function subschemaCode(it2, valid) {
      if (isSchemaObj(it2)) {
        checkKeywords(it2);
        if (schemaCxtHasRules(it2)) {
          subSchemaObjCode(it2, valid);
          return;
        }
      }
      (0, boolSchema_1.boolOrEmptySchema)(it2, valid);
    }
    function schemaCxtHasRules({ schema, self: self2 }) {
      if (typeof schema == "boolean")
        return !schema;
      for (const key in schema)
        if (self2.RULES.all[key])
          return true;
      return false;
    }
    function isSchemaObj(it2) {
      return typeof it2.schema != "boolean";
    }
    function subSchemaObjCode(it2, valid) {
      const { schema, gen, opts } = it2;
      if (opts.$comment && schema.$comment)
        commentKeyword(it2);
      updateContext(it2);
      checkAsyncSchema(it2);
      const errsCount = gen.const("_errs", names_1.default.errors);
      typeAndKeywords(it2, errsCount);
      gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);
    }
    function checkKeywords(it2) {
      (0, util_1.checkUnknownRules)(it2);
      checkRefsAndKeywords(it2);
    }
    function typeAndKeywords(it2, errsCount) {
      if (it2.opts.jtd)
        return schemaKeywords(it2, [], false, errsCount);
      const types2 = (0, dataType_1.getSchemaTypes)(it2.schema);
      const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it2, types2);
      schemaKeywords(it2, types2, !checkedTypes, errsCount);
    }
    function checkRefsAndKeywords(it2) {
      const { schema, errSchemaPath, opts, self: self2 } = it2;
      if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self2.RULES)) {
        self2.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`);
      }
    }
    function checkNoDefault(it2) {
      const { schema, opts } = it2;
      if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) {
        (0, util_1.checkStrictMode)(it2, "default is ignored in the schema root");
      }
    }
    function updateContext(it2) {
      const schId = it2.schema[it2.opts.schemaId];
      if (schId)
        it2.baseId = (0, resolve_1.resolveUrl)(it2.opts.uriResolver, it2.baseId, schId);
    }
    function checkAsyncSchema(it2) {
      if (it2.schema.$async && !it2.schemaEnv.$async)
        throw new Error("async schema in sync schema");
    }
    function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) {
      const msg = schema.$comment;
      if (opts.$comment === true) {
        gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`);
      } else if (typeof opts.$comment == "function") {
        const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`;
        const rootName = gen.scopeValue("root", { ref: schemaEnv.root });
        gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`);
      }
    }
    function returnResults(it2) {
      const { gen, schemaEnv, validateName, ValidationError, opts } = it2;
      if (schemaEnv.$async) {
        gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`));
      } else {
        gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors);
        if (opts.unevaluated)
          assignEvaluated(it2);
        gen.return((0, codegen_1._)`${names_1.default.errors} === 0`);
      }
    }
    function assignEvaluated({ gen, evaluated, props, items: items2 }) {
      if (props instanceof codegen_1.Name)
        gen.assign((0, codegen_1._)`${evaluated}.props`, props);
      if (items2 instanceof codegen_1.Name)
        gen.assign((0, codegen_1._)`${evaluated}.items`, items2);
    }
    function schemaKeywords(it2, types2, typeErrors, errsCount) {
      const { gen, schema, data, allErrors, opts, self: self2 } = it2;
      const { RULES } = self2;
      if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) {
        gen.block(() => keywordCode(it2, "$ref", RULES.all.$ref.definition));
        return;
      }
      if (!opts.jtd)
        checkStrictTypes(it2, types2);
      gen.block(() => {
        for (const group of RULES.rules)
          groupKeywords(group);
        groupKeywords(RULES.post);
      });
      function groupKeywords(group) {
        if (!(0, applicability_1.shouldUseGroup)(schema, group))
          return;
        if (group.type) {
          gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers));
          iterateKeywords(it2, group);
          if (types2.length === 1 && types2[0] === group.type && typeErrors) {
            gen.else();
            (0, dataType_2.reportTypeError)(it2);
          }
          gen.endIf();
        } else {
          iterateKeywords(it2, group);
        }
        if (!allErrors)
          gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`);
      }
    }
    function iterateKeywords(it2, group) {
      const { gen, schema, opts: { useDefaults } } = it2;
      if (useDefaults)
        (0, defaults_1.assignDefaults)(it2, group.type);
      gen.block(() => {
        for (const rule of group.rules) {
          if ((0, applicability_1.shouldUseRule)(schema, rule)) {
            keywordCode(it2, rule.keyword, rule.definition, group.type);
          }
        }
      });
    }
    function checkStrictTypes(it2, types2) {
      if (it2.schemaEnv.meta || !it2.opts.strictTypes)
        return;
      checkContextTypes(it2, types2);
      if (!it2.opts.allowUnionTypes)
        checkMultipleTypes(it2, types2);
      checkKeywordTypes(it2, it2.dataTypes);
    }
    function checkContextTypes(it2, types2) {
      if (!types2.length)
        return;
      if (!it2.dataTypes.length) {
        it2.dataTypes = types2;
        return;
      }
      types2.forEach((t) => {
        if (!includesType(it2.dataTypes, t)) {
          strictTypesError(it2, `type "${t}" not allowed by context "${it2.dataTypes.join(",")}"`);
        }
      });
      narrowSchemaTypes(it2, types2);
    }
    function checkMultipleTypes(it2, ts) {
      if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) {
        strictTypesError(it2, "use allowUnionTypes to allow union type keyword");
      }
    }
    function checkKeywordTypes(it2, ts) {
      const rules2 = it2.self.RULES.all;
      for (const keyword2 in rules2) {
        const rule = rules2[keyword2];
        if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it2.schema, rule)) {
          const { type: type2 } = rule.definition;
          if (type2.length && !type2.some((t) => hasApplicableType(ts, t))) {
            strictTypesError(it2, `missing type "${type2.join(",")}" for keyword "${keyword2}"`);
          }
        }
      }
    }
    function hasApplicableType(schTs, kwdT) {
      return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer");
    }
    function includesType(ts, t) {
      return ts.includes(t) || t === "integer" && ts.includes("number");
    }
    function narrowSchemaTypes(it2, withTypes) {
      const ts = [];
      for (const t of it2.dataTypes) {
        if (includesType(withTypes, t))
          ts.push(t);
        else if (withTypes.includes("integer") && t === "number")
          ts.push("integer");
      }
      it2.dataTypes = ts;
    }
    function strictTypesError(it2, msg) {
      const schemaPath = it2.schemaEnv.baseId + it2.errSchemaPath;
      msg += ` at "${schemaPath}" (strictTypes)`;
      (0, util_1.checkStrictMode)(it2, msg, it2.opts.strictTypes);
    }
    class KeywordCxt {
      constructor(it2, def, keyword2) {
        (0, keyword_1.validateKeywordUsage)(it2, def, keyword2);
        this.gen = it2.gen;
        this.allErrors = it2.allErrors;
        this.keyword = keyword2;
        this.data = it2.data;
        this.schema = it2.schema[keyword2];
        this.$data = def.$data && it2.opts.$data && this.schema && this.schema.$data;
        this.schemaValue = (0, util_1.schemaRefOrVal)(it2, this.schema, keyword2, this.$data);
        this.schemaType = def.schemaType;
        this.parentSchema = it2.schema;
        this.params = {};
        this.it = it2;
        this.def = def;
        if (this.$data) {
          this.schemaCode = it2.gen.const("vSchema", getData(this.$data, it2));
        } else {
          this.schemaCode = this.schemaValue;
          if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) {
            throw new Error(`${keyword2} value must be ${JSON.stringify(def.schemaType)}`);
          }
        }
        if ("code" in def ? def.trackErrors : def.errors !== false) {
          this.errsCount = it2.gen.const("_errs", names_1.default.errors);
        }
      }
      result(condition, successAction, failAction) {
        this.failResult((0, codegen_1.not)(condition), successAction, failAction);
      }
      failResult(condition, successAction, failAction) {
        this.gen.if(condition);
        if (failAction)
          failAction();
        else
          this.error();
        if (successAction) {
          this.gen.else();
          successAction();
          if (this.allErrors)
            this.gen.endIf();
        } else {
          if (this.allErrors)
            this.gen.endIf();
          else
            this.gen.else();
        }
      }
      pass(condition, failAction) {
        this.failResult((0, codegen_1.not)(condition), void 0, failAction);
      }
      fail(condition) {
        if (condition === void 0) {
          this.error();
          if (!this.allErrors)
            this.gen.if(false);
          return;
        }
        this.gen.if(condition);
        this.error();
        if (this.allErrors)
          this.gen.endIf();
        else
          this.gen.else();
      }
      fail$data(condition) {
        if (!this.$data)
          return this.fail(condition);
        const { schemaCode } = this;
        this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`);
      }
      error(append, errorParams, errorPaths) {
        if (errorParams) {
          this.setParams(errorParams);
          this._error(append, errorPaths);
          this.setParams({});
          return;
        }
        this._error(append, errorPaths);
      }
      _error(append, errorPaths) {
        (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths);
      }
      $dataError() {
        (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError);
      }
      reset() {
        if (this.errsCount === void 0)
          throw new Error('add "trackErrors" to keyword definition');
        (0, errors_1.resetErrorsCount)(this.gen, this.errsCount);
      }
      ok(cond) {
        if (!this.allErrors)
          this.gen.if(cond);
      }
      setParams(obj, assign) {
        if (assign)
          Object.assign(this.params, obj);
        else
          this.params = obj;
      }
      block$data(valid, codeBlock, $dataValid = codegen_1.nil) {
        this.gen.block(() => {
          this.check$data(valid, $dataValid);
          codeBlock();
        });
      }
      check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) {
        if (!this.$data)
          return;
        const { gen, schemaCode, schemaType, def } = this;
        gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid));
        if (valid !== codegen_1.nil)
          gen.assign(valid, true);
        if (schemaType.length || def.validateSchema) {
          gen.elseIf(this.invalid$data());
          this.$dataError();
          if (valid !== codegen_1.nil)
            gen.assign(valid, false);
        }
        gen.else();
      }
      invalid$data() {
        const { gen, schemaCode, schemaType, def, it: it2 } = this;
        return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema());
        function wrong$DataType() {
          if (schemaType.length) {
            if (!(schemaCode instanceof codegen_1.Name))
              throw new Error("ajv implementation error");
            const st = Array.isArray(schemaType) ? schemaType : [schemaType];
            return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it2.opts.strictNumbers, dataType_2.DataType.Wrong)}`;
          }
          return codegen_1.nil;
        }
        function invalid$DataSchema() {
          if (def.validateSchema) {
            const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema });
            return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`;
          }
          return codegen_1.nil;
        }
      }
      subschema(appl, valid) {
        const subschema2 = (0, subschema_1.getSubschema)(this.it, appl);
        (0, subschema_1.extendSubschemaData)(subschema2, this.it, appl);
        (0, subschema_1.extendSubschemaMode)(subschema2, appl);
        const nextContext = __spreadProps(__spreadValues(__spreadValues({}, this.it), subschema2), { items: void 0, props: void 0 });
        subschemaCode(nextContext, valid);
        return nextContext;
      }
      mergeEvaluated(schemaCxt, toName) {
        const { it: it2, gen } = this;
        if (!it2.opts.unevaluated)
          return;
        if (it2.props !== true && schemaCxt.props !== void 0) {
          it2.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it2.props, toName);
        }
        if (it2.items !== true && schemaCxt.items !== void 0) {
          it2.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it2.items, toName);
        }
      }
      mergeValidEvaluated(schemaCxt, valid) {
        const { it: it2, gen } = this;
        if (it2.opts.unevaluated && (it2.props !== true || it2.items !== true)) {
          gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name));
          return true;
        }
      }
    }
    validate.KeywordCxt = KeywordCxt;
    function keywordCode(it2, keyword2, def, ruleType) {
      const cxt = new KeywordCxt(it2, def, keyword2);
      if ("code" in def) {
        def.code(cxt, ruleType);
      } else if (cxt.$data && def.validate) {
        (0, keyword_1.funcKeywordCode)(cxt, def);
      } else if ("macro" in def) {
        (0, keyword_1.macroKeywordCode)(cxt, def);
      } else if (def.compile || def.validate) {
        (0, keyword_1.funcKeywordCode)(cxt, def);
      }
    }
    const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
    const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
    function getData($data, { dataLevel, dataNames, dataPathArr }) {
      let jsonPointer;
      let data;
      if ($data === "")
        return names_1.default.rootData;
      if ($data[0] === "/") {
        if (!JSON_POINTER.test($data))
          throw new Error(`Invalid JSON-pointer: ${$data}`);
        jsonPointer = $data;
        data = names_1.default.rootData;
      } else {
        const matches = RELATIVE_JSON_POINTER.exec($data);
        if (!matches)
          throw new Error(`Invalid JSON-pointer: ${$data}`);
        const up = +matches[1];
        jsonPointer = matches[2];
        if (jsonPointer === "#") {
          if (up >= dataLevel)
            throw new Error(errorMsg("property/index", up));
          return dataPathArr[dataLevel - up];
        }
        if (up > dataLevel)
          throw new Error(errorMsg("data", up));
        data = dataNames[dataLevel - up];
        if (!jsonPointer)
          return data;
      }
      let expr = data;
      const segments = jsonPointer.split("/");
      for (const segment of segments) {
        if (segment) {
          data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`;
          expr = (0, codegen_1._)`${expr} && ${data}`;
        }
      }
      return expr;
      function errorMsg(pointerType, up) {
        return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`;
      }
    }
    validate.getData = getData;
    return validate;
  }
  var validation_error = {};
  var hasRequiredValidation_error;
  function requireValidation_error() {
    if (hasRequiredValidation_error) return validation_error;
    hasRequiredValidation_error = 1;
    Object.defineProperty(validation_error, "__esModule", { value: true });
    class ValidationError extends Error {
      constructor(errors2) {
        super("validation failed");
        this.errors = errors2;
        this.ajv = this.validation = true;
      }
    }
    validation_error.default = ValidationError;
    return validation_error;
  }
  var ref_error = {};
  var hasRequiredRef_error;
  function requireRef_error() {
    if (hasRequiredRef_error) return ref_error;
    hasRequiredRef_error = 1;
    Object.defineProperty(ref_error, "__esModule", { value: true });
    const resolve_1 = requireResolve();
    class MissingRefError extends Error {
      constructor(resolver, baseId, ref2, msg) {
        super(msg || `can't resolve reference ${ref2} from id ${baseId}`);
        this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref2);
        this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef));
      }
    }
    ref_error.default = MissingRefError;
    return ref_error;
  }
  var compile = {};
  var hasRequiredCompile;
  function requireCompile() {
    if (hasRequiredCompile) return compile;
    hasRequiredCompile = 1;
    Object.defineProperty(compile, "__esModule", { value: true });
    compile.resolveSchema = compile.getCompilingSchema = compile.resolveRef = compile.compileSchema = compile.SchemaEnv = void 0;
    const codegen_1 = requireCodegen();
    const validation_error_1 = requireValidation_error();
    const names_1 = requireNames();
    const resolve_1 = requireResolve();
    const util_1 = requireUtil();
    const validate_1 = requireValidate();
    class SchemaEnv {
      constructor(env2) {
        var _a3;
        this.refs = {};
        this.dynamicAnchors = {};
        let schema;
        if (typeof env2.schema == "object")
          schema = env2.schema;
        this.schema = env2.schema;
        this.schemaId = env2.schemaId;
        this.root = env2.root || this;
        this.baseId = (_a3 = env2.baseId) !== null && _a3 !== void 0 ? _a3 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env2.schemaId || "$id"]);
        this.schemaPath = env2.schemaPath;
        this.localRefs = env2.localRefs;
        this.meta = env2.meta;
        this.$async = schema === null || schema === void 0 ? void 0 : schema.$async;
        this.refs = {};
      }
    }
    compile.SchemaEnv = SchemaEnv;
    function compileSchema(sch) {
      const _sch = getCompilingSchema.call(this, sch);
      if (_sch)
        return _sch;
      const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId);
      const { es5, lines } = this.opts.code;
      const { ownProperties } = this.opts;
      const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });
      let _ValidationError;
      if (sch.$async) {
        _ValidationError = gen.scopeValue("Error", {
          ref: validation_error_1.default,
          code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default`
        });
      }
      const validateName = gen.scopeName("validate");
      sch.validateName = validateName;
      const schemaCxt = {
        gen,
        allErrors: this.opts.allErrors,
        data: names_1.default.data,
        parentData: names_1.default.parentData,
        parentDataProperty: names_1.default.parentDataProperty,
        dataNames: [names_1.default.data],
        dataPathArr: [codegen_1.nil],
        // TODO can its length be used as dataLevel if nil is removed?
        dataLevel: 0,
        dataTypes: [],
        definedProperties: /* @__PURE__ */ new Set(),
        topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) } : { ref: sch.schema }),
        validateName,
        ValidationError: _ValidationError,
        schema: sch.schema,
        schemaEnv: sch,
        rootId,
        baseId: sch.baseId || rootId,
        schemaPath: codegen_1.nil,
        errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"),
        errorPath: (0, codegen_1._)`""`,
        opts: this.opts,
        self: this
      };
      let sourceCode;
      try {
        this._compilations.add(sch);
        (0, validate_1.validateFunctionCode)(schemaCxt);
        gen.optimize(this.opts.code.optimize);
        const validateCode = gen.toString();
        sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`;
        if (this.opts.code.process)
          sourceCode = this.opts.code.process(sourceCode, sch);
        const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode);
        const validate2 = makeValidate(this, this.scope.get());
        this.scope.value(validateName, { ref: validate2 });
        validate2.errors = null;
        validate2.schema = sch.schema;
        validate2.schemaEnv = sch;
        if (sch.$async)
          validate2.$async = true;
        if (this.opts.code.source === true) {
          validate2.source = { validateName, validateCode, scopeValues: gen._values };
        }
        if (this.opts.unevaluated) {
          const { props, items: items2 } = schemaCxt;
          validate2.evaluated = {
            props: props instanceof codegen_1.Name ? void 0 : props,
            items: items2 instanceof codegen_1.Name ? void 0 : items2,
            dynamicProps: props instanceof codegen_1.Name,
            dynamicItems: items2 instanceof codegen_1.Name
          };
          if (validate2.source)
            validate2.source.evaluated = (0, codegen_1.stringify)(validate2.evaluated);
        }
        sch.validate = validate2;
        return sch;
      } catch (e) {
        delete sch.validate;
        delete sch.validateName;
        if (sourceCode)
          this.logger.error("Error compiling schema, function code:", sourceCode);
        throw e;
      } finally {
        this._compilations.delete(sch);
      }
    }
    compile.compileSchema = compileSchema;
    function resolveRef2(root, baseId, ref2) {
      var _a3;
      ref2 = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref2);
      const schOrFunc = root.refs[ref2];
      if (schOrFunc)
        return schOrFunc;
      let _sch = resolve2.call(this, root, ref2);
      if (_sch === void 0) {
        const schema = (_a3 = root.localRefs) === null || _a3 === void 0 ? void 0 : _a3[ref2];
        const { schemaId } = this.opts;
        if (schema)
          _sch = new SchemaEnv({ schema, schemaId, root, baseId });
      }
      if (_sch === void 0)
        return;
      return root.refs[ref2] = inlineOrCompile.call(this, _sch);
    }
    compile.resolveRef = resolveRef2;
    function inlineOrCompile(sch) {
      if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs))
        return sch.schema;
      return sch.validate ? sch : compileSchema.call(this, sch);
    }
    function getCompilingSchema(schEnv) {
      for (const sch of this._compilations) {
        if (sameSchemaEnv(sch, schEnv))
          return sch;
      }
    }
    compile.getCompilingSchema = getCompilingSchema;
    function sameSchemaEnv(s1, s2) {
      return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
    }
    function resolve2(root, ref2) {
      let sch;
      while (typeof (sch = this.refs[ref2]) == "string")
        ref2 = sch;
      return sch || this.schemas[ref2] || resolveSchema.call(this, root, ref2);
    }
    function resolveSchema(root, ref2) {
      const p = this.opts.uriResolver.parse(ref2);
      const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p);
      let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0);
      if (Object.keys(root.schema).length > 0 && refPath === baseId) {
        return getJsonPointer.call(this, p, root);
      }
      const id2 = (0, resolve_1.normalizeId)(refPath);
      const schOrRef = this.refs[id2] || this.schemas[id2];
      if (typeof schOrRef == "string") {
        const sch = resolveSchema.call(this, root, schOrRef);
        if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object")
          return;
        return getJsonPointer.call(this, p, sch);
      }
      if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object")
        return;
      if (!schOrRef.validate)
        compileSchema.call(this, schOrRef);
      if (id2 === (0, resolve_1.normalizeId)(ref2)) {
        const { schema } = schOrRef;
        const { schemaId } = this.opts;
        const schId = schema[schemaId];
        if (schId)
          baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
        return new SchemaEnv({ schema, schemaId, root, baseId });
      }
      return getJsonPointer.call(this, p, schOrRef);
    }
    compile.resolveSchema = resolveSchema;
    const PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([
      "properties",
      "patternProperties",
      "enum",
      "dependencies",
      "definitions"
    ]);
    function getJsonPointer(parsedRef, { baseId, schema, root }) {
      var _a3;
      if (((_a3 = parsedRef.fragment) === null || _a3 === void 0 ? void 0 : _a3[0]) !== "/")
        return;
      for (const part of parsedRef.fragment.slice(1).split("/")) {
        if (typeof schema === "boolean")
          return;
        const partSchema = schema[(0, util_1.unescapeFragment)(part)];
        if (partSchema === void 0)
          return;
        schema = partSchema;
        const schId = typeof schema === "object" && schema[this.opts.schemaId];
        if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {
          baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
        }
      }
      let env2;
      if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) {
        const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref);
        env2 = resolveSchema.call(this, root, $ref);
      }
      const { schemaId } = this.opts;
      env2 = env2 || new SchemaEnv({ schema, schemaId, root, baseId });
      if (env2.schema !== env2.root.schema)
        return env2;
      return void 0;
    }
    return compile;
  }
  const $id$1 = "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#";
  const description = "Meta-schema for $data reference (JSON AnySchema extension proposal)";
  const type$1 = "object";
  const required$1 = ["$data"];
  const properties$2 = { "$data": { "type": "string", "anyOf": [{ "format": "relative-json-pointer" }, { "format": "json-pointer" }] } };
  const additionalProperties$1 = false;
  const require$$9 = {
    $id: $id$1,
    description,
    type: type$1,
    required: required$1,
    properties: properties$2,
    additionalProperties: additionalProperties$1
  };
  var uri = {};
  var fastUri = { exports: {} };
  var utils;
  var hasRequiredUtils;
  function requireUtils() {
    if (hasRequiredUtils) return utils;
    hasRequiredUtils = 1;
    const isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu);
    const isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);
    function stringArrayToHexStripped(input) {
      let acc = "";
      let code2 = 0;
      let i2 = 0;
      for (i2 = 0; i2 < input.length; i2++) {
        code2 = input[i2].charCodeAt(0);
        if (code2 === 48) {
          continue;
        }
        if (!(code2 >= 48 && code2 <= 57 || code2 >= 65 && code2 <= 70 || code2 >= 97 && code2 <= 102)) {
          return "";
        }
        acc += input[i2];
        break;
      }
      for (i2 += 1; i2 < input.length; i2++) {
        code2 = input[i2].charCodeAt(0);
        if (!(code2 >= 48 && code2 <= 57 || code2 >= 65 && code2 <= 70 || code2 >= 97 && code2 <= 102)) {
          return "";
        }
        acc += input[i2];
      }
      return acc;
    }
    const nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);
    function consumeIsZone(buffer2) {
      buffer2.length = 0;
      return true;
    }
    function consumeHextets(buffer2, address, output) {
      if (buffer2.length) {
        const hex2 = stringArrayToHexStripped(buffer2);
        if (hex2 !== "") {
          address.push(hex2);
        } else {
          output.error = true;
          return false;
        }
        buffer2.length = 0;
      }
      return true;
    }
    function getIPV6(input) {
      let tokenCount = 0;
      const output = { error: false, address: "", zone: "" };
      const address = [];
      const buffer2 = [];
      let endipv6Encountered = false;
      let endIpv6 = false;
      let consume = consumeHextets;
      for (let i2 = 0; i2 < input.length; i2++) {
        const cursor = input[i2];
        if (cursor === "[" || cursor === "]") {
          continue;
        }
        if (cursor === ":") {
          if (endipv6Encountered === true) {
            endIpv6 = true;
          }
          if (!consume(buffer2, address, output)) {
            break;
          }
          if (++tokenCount > 7) {
            output.error = true;
            break;
          }
          if (i2 > 0 && input[i2 - 1] === ":") {
            endipv6Encountered = true;
          }
          address.push(":");
          continue;
        } else if (cursor === "%") {
          if (!consume(buffer2, address, output)) {
            break;
          }
          consume = consumeIsZone;
        } else {
          buffer2.push(cursor);
          continue;
        }
      }
      if (buffer2.length) {
        if (consume === consumeIsZone) {
          output.zone = buffer2.join("");
        } else if (endIpv6) {
          address.push(buffer2.join(""));
        } else {
          address.push(stringArrayToHexStripped(buffer2));
        }
      }
      output.address = address.join("");
      return output;
    }
    function normalizeIPv6(host) {
      if (findToken(host, ":") < 2) {
        return { host, isIPV6: false };
      }
      const ipv62 = getIPV6(host);
      if (!ipv62.error) {
        let newHost = ipv62.address;
        let escapedHost = ipv62.address;
        if (ipv62.zone) {
          newHost += "%" + ipv62.zone;
          escapedHost += "%25" + ipv62.zone;
        }
        return { host: newHost, isIPV6: true, escapedHost };
      } else {
        return { host, isIPV6: false };
      }
    }
    function findToken(str, token) {
      let ind = 0;
      for (let i2 = 0; i2 < str.length; i2++) {
        if (str[i2] === token) ind++;
      }
      return ind;
    }
    function removeDotSegments(path) {
      let input = path;
      const output = [];
      let nextSlash = -1;
      let len2 = 0;
      while (len2 = input.length) {
        if (len2 === 1) {
          if (input === ".") {
            break;
          } else if (input === "/") {
            output.push("/");
            break;
          } else {
            output.push(input);
            break;
          }
        } else if (len2 === 2) {
          if (input[0] === ".") {
            if (input[1] === ".") {
              break;
            } else if (input[1] === "/") {
              input = input.slice(2);
              continue;
            }
          } else if (input[0] === "/") {
            if (input[1] === "." || input[1] === "/") {
              output.push("/");
              break;
            }
          }
        } else if (len2 === 3) {
          if (input === "/..") {
            if (output.length !== 0) {
              output.pop();
            }
            output.push("/");
            break;
          }
        }
        if (input[0] === ".") {
          if (input[1] === ".") {
            if (input[2] === "/") {
              input = input.slice(3);
              continue;
            }
          } else if (input[1] === "/") {
            input = input.slice(2);
            continue;
          }
        } else if (input[0] === "/") {
          if (input[1] === ".") {
            if (input[2] === "/") {
              input = input.slice(2);
              continue;
            } else if (input[2] === ".") {
              if (input[3] === "/") {
                input = input.slice(3);
                if (output.length !== 0) {
                  output.pop();
                }
                continue;
              }
            }
          }
        }
        if ((nextSlash = input.indexOf("/", 1)) === -1) {
          output.push(input);
          break;
        } else {
          output.push(input.slice(0, nextSlash));
          input = input.slice(nextSlash);
        }
      }
      return output.join("");
    }
    function normalizeComponentEncoding(component, esc2) {
      const func = esc2 !== true ? escape : unescape;
      if (component.scheme !== void 0) {
        component.scheme = func(component.scheme);
      }
      if (component.userinfo !== void 0) {
        component.userinfo = func(component.userinfo);
      }
      if (component.host !== void 0) {
        component.host = func(component.host);
      }
      if (component.path !== void 0) {
        component.path = func(component.path);
      }
      if (component.query !== void 0) {
        component.query = func(component.query);
      }
      if (component.fragment !== void 0) {
        component.fragment = func(component.fragment);
      }
      return component;
    }
    function recomposeAuthority(component) {
      const uriTokens = [];
      if (component.userinfo !== void 0) {
        uriTokens.push(component.userinfo);
        uriTokens.push("@");
      }
      if (component.host !== void 0) {
        let host = unescape(component.host);
        if (!isIPv4(host)) {
          const ipV6res = normalizeIPv6(host);
          if (ipV6res.isIPV6 === true) {
            host = `[${ipV6res.escapedHost}]`;
          } else {
            host = component.host;
          }
        }
        uriTokens.push(host);
      }
      if (typeof component.port === "number" || typeof component.port === "string") {
        uriTokens.push(":");
        uriTokens.push(String(component.port));
      }
      return uriTokens.length ? uriTokens.join("") : void 0;
    }
    utils = {
      nonSimpleDomain,
      recomposeAuthority,
      normalizeComponentEncoding,
      removeDotSegments,
      isIPv4,
      isUUID,
      normalizeIPv6,
      stringArrayToHexStripped
    };
    return utils;
  }
  var schemes;
  var hasRequiredSchemes;
  function requireSchemes() {
    if (hasRequiredSchemes) return schemes;
    hasRequiredSchemes = 1;
    const { isUUID } = requireUtils();
    const URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;
    const supportedSchemeNames = (
      /** @type {const} */
      [
        "http",
        "https",
        "ws",
        "wss",
        "urn",
        "urn:uuid"
      ]
    );
    function isValidSchemeName(name2) {
      return supportedSchemeNames.indexOf(
        /** @type {*} */
        name2
      ) !== -1;
    }
    function wsIsSecure(wsComponent) {
      if (wsComponent.secure === true) {
        return true;
      } else if (wsComponent.secure === false) {
        return false;
      } else if (wsComponent.scheme) {
        return wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === "w" || wsComponent.scheme[0] === "W") && (wsComponent.scheme[1] === "s" || wsComponent.scheme[1] === "S") && (wsComponent.scheme[2] === "s" || wsComponent.scheme[2] === "S");
      } else {
        return false;
      }
    }
    function httpParse(component) {
      if (!component.host) {
        component.error = component.error || "HTTP URIs must have a host.";
      }
      return component;
    }
    function httpSerialize(component) {
      const secure = String(component.scheme).toLowerCase() === "https";
      if (component.port === (secure ? 443 : 80) || component.port === "") {
        component.port = void 0;
      }
      if (!component.path) {
        component.path = "/";
      }
      return component;
    }
    function wsParse(wsComponent) {
      wsComponent.secure = wsIsSecure(wsComponent);
      wsComponent.resourceName = (wsComponent.path || "/") + (wsComponent.query ? "?" + wsComponent.query : "");
      wsComponent.path = void 0;
      wsComponent.query = void 0;
      return wsComponent;
    }
    function wsSerialize(wsComponent) {
      if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === "") {
        wsComponent.port = void 0;
      }
      if (typeof wsComponent.secure === "boolean") {
        wsComponent.scheme = wsComponent.secure ? "wss" : "ws";
        wsComponent.secure = void 0;
      }
      if (wsComponent.resourceName) {
        const [path, query] = wsComponent.resourceName.split("?");
        wsComponent.path = path && path !== "/" ? path : void 0;
        wsComponent.query = query;
        wsComponent.resourceName = void 0;
      }
      wsComponent.fragment = void 0;
      return wsComponent;
    }
    function urnParse(urnComponent, options) {
      if (!urnComponent.path) {
        urnComponent.error = "URN can not be parsed";
        return urnComponent;
      }
      const matches = urnComponent.path.match(URN_REG);
      if (matches) {
        const scheme = options.scheme || urnComponent.scheme || "urn";
        urnComponent.nid = matches[1].toLowerCase();
        urnComponent.nss = matches[2];
        const urnScheme = `${scheme}:${options.nid || urnComponent.nid}`;
        const schemeHandler = getSchemeHandler(urnScheme);
        urnComponent.path = void 0;
        if (schemeHandler) {
          urnComponent = schemeHandler.parse(urnComponent, options);
        }
      } else {
        urnComponent.error = urnComponent.error || "URN can not be parsed.";
      }
      return urnComponent;
    }
    function urnSerialize(urnComponent, options) {
      if (urnComponent.nid === void 0) {
        throw new Error("URN without nid cannot be serialized");
      }
      const scheme = options.scheme || urnComponent.scheme || "urn";
      const nid = urnComponent.nid.toLowerCase();
      const urnScheme = `${scheme}:${options.nid || nid}`;
      const schemeHandler = getSchemeHandler(urnScheme);
      if (schemeHandler) {
        urnComponent = schemeHandler.serialize(urnComponent, options);
      }
      const uriComponent = urnComponent;
      const nss = urnComponent.nss;
      uriComponent.path = `${nid || options.nid}:${nss}`;
      options.skipEscape = true;
      return uriComponent;
    }
    function urnuuidParse(urnComponent, options) {
      const uuidComponent = urnComponent;
      uuidComponent.uuid = uuidComponent.nss;
      uuidComponent.nss = void 0;
      if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) {
        uuidComponent.error = uuidComponent.error || "UUID is not valid.";
      }
      return uuidComponent;
    }
    function urnuuidSerialize(uuidComponent) {
      const urnComponent = uuidComponent;
      urnComponent.nss = (uuidComponent.uuid || "").toLowerCase();
      return urnComponent;
    }
    const http = (
      /** @type {SchemeHandler} */
      {
        scheme: "http",
        domainHost: true,
        parse: httpParse,
        serialize: httpSerialize
      }
    );
    const https = (
      /** @type {SchemeHandler} */
      {
        scheme: "https",
        domainHost: http.domainHost,
        parse: httpParse,
        serialize: httpSerialize
      }
    );
    const ws = (
      /** @type {SchemeHandler} */
      {
        scheme: "ws",
        domainHost: true,
        parse: wsParse,
        serialize: wsSerialize
      }
    );
    const wss = (
      /** @type {SchemeHandler} */
      {
        scheme: "wss",
        domainHost: ws.domainHost,
        parse: ws.parse,
        serialize: ws.serialize
      }
    );
    const urn = (
      /** @type {SchemeHandler} */
      {
        scheme: "urn",
        parse: urnParse,
        serialize: urnSerialize,
        skipNormalize: true
      }
    );
    const urnuuid = (
      /** @type {SchemeHandler} */
      {
        scheme: "urn:uuid",
        parse: urnuuidParse,
        serialize: urnuuidSerialize,
        skipNormalize: true
      }
    );
    const SCHEMES = (
      /** @type {Record<SchemeName, SchemeHandler>} */
      {
        http,
        https,
        ws,
        wss,
        urn,
        "urn:uuid": urnuuid
      }
    );
    Object.setPrototypeOf(SCHEMES, null);
    function getSchemeHandler(scheme) {
      return scheme && (SCHEMES[
        /** @type {SchemeName} */
        scheme
      ] || SCHEMES[
        /** @type {SchemeName} */
        scheme.toLowerCase()
      ]) || void 0;
    }
    schemes = {
      wsIsSecure,
      SCHEMES,
      isValidSchemeName,
      getSchemeHandler
    };
    return schemes;
  }
  var hasRequiredFastUri;
  function requireFastUri() {
    if (hasRequiredFastUri) return fastUri.exports;
    hasRequiredFastUri = 1;
    const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = requireUtils();
    const { SCHEMES, getSchemeHandler } = requireSchemes();
    function normalize(uri2, options) {
      if (typeof uri2 === "string") {
        uri2 = /** @type {T} */
        serialize(parse2(uri2, options), options);
      } else if (typeof uri2 === "object") {
        uri2 = /** @type {T} */
        parse2(serialize(uri2, options), options);
      }
      return uri2;
    }
    function resolve2(baseURI, relativeURI, options) {
      const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
      const resolved = resolveComponent(parse2(baseURI, schemelessOptions), parse2(relativeURI, schemelessOptions), schemelessOptions, true);
      schemelessOptions.skipEscape = true;
      return serialize(resolved, schemelessOptions);
    }
    function resolveComponent(base, relative, options, skipNormalization) {
      const target = {};
      if (!skipNormalization) {
        base = parse2(serialize(base, options), options);
        relative = parse2(serialize(relative, options), options);
      }
      options = options || {};
      if (!options.tolerant && relative.scheme) {
        target.scheme = relative.scheme;
        target.userinfo = relative.userinfo;
        target.host = relative.host;
        target.port = relative.port;
        target.path = removeDotSegments(relative.path || "");
        target.query = relative.query;
      } else {
        if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) {
          target.userinfo = relative.userinfo;
          target.host = relative.host;
          target.port = relative.port;
          target.path = removeDotSegments(relative.path || "");
          target.query = relative.query;
        } else {
          if (!relative.path) {
            target.path = base.path;
            if (relative.query !== void 0) {
              target.query = relative.query;
            } else {
              target.query = base.query;
            }
          } else {
            if (relative.path[0] === "/") {
              target.path = removeDotSegments(relative.path);
            } else {
              if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) {
                target.path = "/" + relative.path;
              } else if (!base.path) {
                target.path = relative.path;
              } else {
                target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path;
              }
              target.path = removeDotSegments(target.path);
            }
            target.query = relative.query;
          }
          target.userinfo = base.userinfo;
          target.host = base.host;
          target.port = base.port;
        }
        target.scheme = base.scheme;
      }
      target.fragment = relative.fragment;
      return target;
    }
    function equal2(uriA, uriB, options) {
      if (typeof uriA === "string") {
        uriA = unescape(uriA);
        uriA = serialize(normalizeComponentEncoding(parse2(uriA, options), true), __spreadProps(__spreadValues({}, options), { skipEscape: true }));
      } else if (typeof uriA === "object") {
        uriA = serialize(normalizeComponentEncoding(uriA, true), __spreadProps(__spreadValues({}, options), { skipEscape: true }));
      }
      if (typeof uriB === "string") {
        uriB = unescape(uriB);
        uriB = serialize(normalizeComponentEncoding(parse2(uriB, options), true), __spreadProps(__spreadValues({}, options), { skipEscape: true }));
      } else if (typeof uriB === "object") {
        uriB = serialize(normalizeComponentEncoding(uriB, true), __spreadProps(__spreadValues({}, options), { skipEscape: true }));
      }
      return uriA.toLowerCase() === uriB.toLowerCase();
    }
    function serialize(cmpts, opts) {
      const component = {
        host: cmpts.host,
        scheme: cmpts.scheme,
        userinfo: cmpts.userinfo,
        port: cmpts.port,
        path: cmpts.path,
        query: cmpts.query,
        nid: cmpts.nid,
        nss: cmpts.nss,
        uuid: cmpts.uuid,
        fragment: cmpts.fragment,
        reference: cmpts.reference,
        resourceName: cmpts.resourceName,
        secure: cmpts.secure,
        error: ""
      };
      const options = Object.assign({}, opts);
      const uriTokens = [];
      const schemeHandler = getSchemeHandler(options.scheme || component.scheme);
      if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options);
      if (component.path !== void 0) {
        if (!options.skipEscape) {
          component.path = escape(component.path);
          if (component.scheme !== void 0) {
            component.path = component.path.split("%3A").join(":");
          }
        } else {
          component.path = unescape(component.path);
        }
      }
      if (options.reference !== "suffix" && component.scheme) {
        uriTokens.push(component.scheme, ":");
      }
      const authority = recomposeAuthority(component);
      if (authority !== void 0) {
        if (options.reference !== "suffix") {
          uriTokens.push("//");
        }
        uriTokens.push(authority);
        if (component.path && component.path[0] !== "/") {
          uriTokens.push("/");
        }
      }
      if (component.path !== void 0) {
        let s = component.path;
        if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {
          s = removeDotSegments(s);
        }
        if (authority === void 0 && s[0] === "/" && s[1] === "/") {
          s = "/%2F" + s.slice(2);
        }
        uriTokens.push(s);
      }
      if (component.query !== void 0) {
        uriTokens.push("?", component.query);
      }
      if (component.fragment !== void 0) {
        uriTokens.push("#", component.fragment);
      }
      return uriTokens.join("");
    }
    const URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;
    function parse2(uri2, opts) {
      const options = Object.assign({}, opts);
      const parsed = {
        scheme: void 0,
        userinfo: void 0,
        host: "",
        port: void 0,
        path: "",
        query: void 0,
        fragment: void 0
      };
      let isIP = false;
      if (options.reference === "suffix") {
        if (options.scheme) {
          uri2 = options.scheme + ":" + uri2;
        } else {
          uri2 = "//" + uri2;
        }
      }
      const matches = uri2.match(URI_PARSE);
      if (matches) {
        parsed.scheme = matches[1];
        parsed.userinfo = matches[3];
        parsed.host = matches[4];
        parsed.port = parseInt(matches[5], 10);
        parsed.path = matches[6] || "";
        parsed.query = matches[7];
        parsed.fragment = matches[8];
        if (isNaN(parsed.port)) {
          parsed.port = matches[5];
        }
        if (parsed.host) {
          const ipv4result = isIPv4(parsed.host);
          if (ipv4result === false) {
            const ipv6result = normalizeIPv6(parsed.host);
            parsed.host = ipv6result.host.toLowerCase();
            isIP = ipv6result.isIPV6;
          } else {
            isIP = true;
          }
        }
        if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) {
          parsed.reference = "same-document";
        } else if (parsed.scheme === void 0) {
          parsed.reference = "relative";
        } else if (parsed.fragment === void 0) {
          parsed.reference = "absolute";
        } else {
          parsed.reference = "uri";
        }
        if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) {
          parsed.error = parsed.error || "URI is not a " + options.reference + " reference.";
        }
        const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme);
        if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {
          if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) {
            try {
              parsed.host = URL.domainToASCII(parsed.host.toLowerCase());
            } catch (e) {
              parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e;
            }
          }
        }
        if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) {
          if (uri2.indexOf("%") !== -1) {
            if (parsed.scheme !== void 0) {
              parsed.scheme = unescape(parsed.scheme);
            }
            if (parsed.host !== void 0) {
              parsed.host = unescape(parsed.host);
            }
          }
          if (parsed.path) {
            parsed.path = escape(unescape(parsed.path));
          }
          if (parsed.fragment) {
            parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment));
          }
        }
        if (schemeHandler && schemeHandler.parse) {
          schemeHandler.parse(parsed, options);
        }
      } else {
        parsed.error = parsed.error || "URI can not be parsed.";
      }
      return parsed;
    }
    const fastUri$1 = {
      SCHEMES,
      normalize,
      resolve: resolve2,
      resolveComponent,
      equal: equal2,
      serialize,
      parse: parse2
    };
    fastUri.exports = fastUri$1;
    fastUri.exports.default = fastUri$1;
    fastUri.exports.fastUri = fastUri$1;
    return fastUri.exports;
  }
  var hasRequiredUri;
  function requireUri() {
    if (hasRequiredUri) return uri;
    hasRequiredUri = 1;
    Object.defineProperty(uri, "__esModule", { value: true });
    const uri$1 = requireFastUri();
    uri$1.code = 'require("ajv/dist/runtime/uri").default';
    uri.default = uri$1;
    return uri;
  }
  var hasRequiredCore$1;
  function requireCore$1() {
    if (hasRequiredCore$1) return core$1;
    hasRequiredCore$1 = 1;
    (function(exports$12) {
      Object.defineProperty(exports$12, "__esModule", { value: true });
      exports$12.CodeGen = exports$12.Name = exports$12.nil = exports$12.stringify = exports$12.str = exports$12._ = exports$12.KeywordCxt = void 0;
      var validate_1 = requireValidate();
      Object.defineProperty(exports$12, "KeywordCxt", { enumerable: true, get: function() {
        return validate_1.KeywordCxt;
      } });
      var codegen_1 = requireCodegen();
      Object.defineProperty(exports$12, "_", { enumerable: true, get: function() {
        return codegen_1._;
      } });
      Object.defineProperty(exports$12, "str", { enumerable: true, get: function() {
        return codegen_1.str;
      } });
      Object.defineProperty(exports$12, "stringify", { enumerable: true, get: function() {
        return codegen_1.stringify;
      } });
      Object.defineProperty(exports$12, "nil", { enumerable: true, get: function() {
        return codegen_1.nil;
      } });
      Object.defineProperty(exports$12, "Name", { enumerable: true, get: function() {
        return codegen_1.Name;
      } });
      Object.defineProperty(exports$12, "CodeGen", { enumerable: true, get: function() {
        return codegen_1.CodeGen;
      } });
      const validation_error_1 = requireValidation_error();
      const ref_error_1 = requireRef_error();
      const rules_1 = requireRules();
      const compile_1 = requireCompile();
      const codegen_2 = requireCodegen();
      const resolve_1 = requireResolve();
      const dataType_1 = requireDataType();
      const util_1 = requireUtil();
      const $dataRefSchema = require$$9;
      const uri_1 = requireUri();
      const defaultRegExp = (str, flags) => new RegExp(str, flags);
      defaultRegExp.code = "new RegExp";
      const META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"];
      const EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([
        "validate",
        "serialize",
        "parse",
        "wrapper",
        "root",
        "schema",
        "keyword",
        "pattern",
        "formats",
        "validate$data",
        "func",
        "obj",
        "Error"
      ]);
      const removedOptions = {
        errorDataPath: "",
        format: "`validateFormats: false` can be used instead.",
        nullable: '"nullable" keyword is supported by default.',
        jsonPointers: "Deprecated jsPropertySyntax can be used instead.",
        extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.",
        missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.",
        processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`",
        sourceCode: "Use option `code: {source: true}`",
        strictDefaults: "It is default now, see option `strict`.",
        strictKeywords: "It is default now, see option `strict`.",
        uniqueItems: '"uniqueItems" keyword is always validated.',
        unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",
        cache: "Map is used as cache, schema object as key.",
        serialize: "Map is used as cache, schema object as key.",
        ajvErrors: "It is default now."
      };
      const deprecatedOptions = {
        ignoreKeywordsWithRef: "",
        jsPropertySyntax: "",
        unicode: '"minLength"/"maxLength" account for unicode characters by default.'
      };
      const MAX_EXPRESSION = 200;
      function requiredOptions(o) {
        var _a3, _b2, _c2, _d2, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;
        const s = o.strict;
        const _optz = (_a3 = o.code) === null || _a3 === void 0 ? void 0 : _a3.optimize;
        const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0;
        const regExp = (_c2 = (_b2 = o.code) === null || _b2 === void 0 ? void 0 : _b2.regExp) !== null && _c2 !== void 0 ? _c2 : defaultRegExp;
        const uriResolver = (_d2 = o.uriResolver) !== null && _d2 !== void 0 ? _d2 : uri_1.default;
        return {
          strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true,
          strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true,
          strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log",
          strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log",
          strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false,
          code: o.code ? __spreadProps(__spreadValues({}, o.code), { optimize, regExp }) : { optimize, regExp },
          loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,
          loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION,
          meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true,
          messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true,
          inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true,
          schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id",
          addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true,
          validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true,
          validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true,
          unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true,
          int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true,
          uriResolver
        };
      }
      class Ajv2 {
        constructor(opts = {}) {
          this.schemas = {};
          this.refs = {};
          this.formats = {};
          this._compilations = /* @__PURE__ */ new Set();
          this._loading = {};
          this._cache = /* @__PURE__ */ new Map();
          opts = this.opts = __spreadValues(__spreadValues({}, opts), requiredOptions(opts));
          const { es5, lines } = this.opts.code;
          this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines });
          this.logger = getLogger(opts.logger);
          const formatOpt = opts.validateFormats;
          opts.validateFormats = false;
          this.RULES = (0, rules_1.getRules)();
          checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED");
          checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn");
          this._metaOpts = getMetaSchemaOptions.call(this);
          if (opts.formats)
            addInitialFormats.call(this);
          this._addVocabularies();
          this._addDefaultMetaSchema();
          if (opts.keywords)
            addInitialKeywords.call(this, opts.keywords);
          if (typeof opts.meta == "object")
            this.addMetaSchema(opts.meta);
          addInitialSchemas.call(this);
          opts.validateFormats = formatOpt;
        }
        _addVocabularies() {
          this.addKeyword("$async");
        }
        _addDefaultMetaSchema() {
          const { $data, meta: meta2, schemaId } = this.opts;
          let _dataRefSchema = $dataRefSchema;
          if (schemaId === "id") {
            _dataRefSchema = __spreadValues({}, $dataRefSchema);
            _dataRefSchema.id = _dataRefSchema.$id;
            delete _dataRefSchema.$id;
          }
          if (meta2 && $data)
            this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false);
        }
        defaultMeta() {
          const { meta: meta2, schemaId } = this.opts;
          return this.opts.defaultMeta = typeof meta2 == "object" ? meta2[schemaId] || meta2 : void 0;
        }
        validate(schemaKeyRef, data) {
          let v;
          if (typeof schemaKeyRef == "string") {
            v = this.getSchema(schemaKeyRef);
            if (!v)
              throw new Error(`no schema with key or ref "${schemaKeyRef}"`);
          } else {
            v = this.compile(schemaKeyRef);
          }
          const valid = v(data);
          if (!("$async" in v))
            this.errors = v.errors;
          return valid;
        }
        compile(schema, _meta) {
          const sch = this._addSchema(schema, _meta);
          return sch.validate || this._compileSchemaEnv(sch);
        }
        compileAsync(schema, meta2) {
          if (typeof this.opts.loadSchema != "function") {
            throw new Error("options.loadSchema should be a function");
          }
          const { loadSchema } = this.opts;
          return runCompileAsync.call(this, schema, meta2);
          function runCompileAsync(_schema, _meta) {
            return __async(this, null, function* () {
              yield loadMetaSchema.call(this, _schema.$schema);
              const sch = this._addSchema(_schema, _meta);
              return sch.validate || _compileAsync.call(this, sch);
            });
          }
          function loadMetaSchema($ref) {
            return __async(this, null, function* () {
              if ($ref && !this.getSchema($ref)) {
                yield runCompileAsync.call(this, { $ref }, true);
              }
            });
          }
          function _compileAsync(sch) {
            return __async(this, null, function* () {
              try {
                return this._compileSchemaEnv(sch);
              } catch (e) {
                if (!(e instanceof ref_error_1.default))
                  throw e;
                checkLoaded.call(this, e);
                yield loadMissingSchema.call(this, e.missingSchema);
                return _compileAsync.call(this, sch);
              }
            });
          }
          function checkLoaded({ missingSchema: ref2, missingRef }) {
            if (this.refs[ref2]) {
              throw new Error(`AnySchema ${ref2} is loaded but ${missingRef} cannot be resolved`);
            }
          }
          function loadMissingSchema(ref2) {
            return __async(this, null, function* () {
              const _schema = yield _loadSchema.call(this, ref2);
              if (!this.refs[ref2])
                yield loadMetaSchema.call(this, _schema.$schema);
              if (!this.refs[ref2])
                this.addSchema(_schema, ref2, meta2);
            });
          }
          function _loadSchema(ref2) {
            return __async(this, null, function* () {
              const p = this._loading[ref2];
              if (p)
                return p;
              try {
                return yield this._loading[ref2] = loadSchema(ref2);
              } finally {
                delete this._loading[ref2];
              }
            });
          }
        }
        // Adds schema to the instance
        addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) {
          if (Array.isArray(schema)) {
            for (const sch of schema)
              this.addSchema(sch, void 0, _meta, _validateSchema);
            return this;
          }
          let id2;
          if (typeof schema === "object") {
            const { schemaId } = this.opts;
            id2 = schema[schemaId];
            if (id2 !== void 0 && typeof id2 != "string") {
              throw new Error(`schema ${schemaId} must be string`);
            }
          }
          key = (0, resolve_1.normalizeId)(key || id2);
          this._checkUnique(key);
          this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true);
          return this;
        }
        // Add schema that will be used to validate other schemas
        // options in META_IGNORE_OPTIONS are alway set to false
        addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) {
          this.addSchema(schema, key, true, _validateSchema);
          return this;
        }
        //  Validate schema against its meta-schema
        validateSchema(schema, throwOrLogError) {
          if (typeof schema == "boolean")
            return true;
          let $schema2;
          $schema2 = schema.$schema;
          if ($schema2 !== void 0 && typeof $schema2 != "string") {
            throw new Error("$schema must be a string");
          }
          $schema2 = $schema2 || this.opts.defaultMeta || this.defaultMeta();
          if (!$schema2) {
            this.logger.warn("meta-schema not available");
            this.errors = null;
            return true;
          }
          const valid = this.validate($schema2, schema);
          if (!valid && throwOrLogError) {
            const message = "schema is invalid: " + this.errorsText();
            if (this.opts.validateSchema === "log")
              this.logger.error(message);
            else
              throw new Error(message);
          }
          return valid;
        }
        // Get compiled schema by `key` or `ref`.
        // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)
        getSchema(keyRef) {
          let sch;
          while (typeof (sch = getSchEnv.call(this, keyRef)) == "string")
            keyRef = sch;
          if (sch === void 0) {
            const { schemaId } = this.opts;
            const root = new compile_1.SchemaEnv({ schema: {}, schemaId });
            sch = compile_1.resolveSchema.call(this, root, keyRef);
            if (!sch)
              return;
            this.refs[keyRef] = sch;
          }
          return sch.validate || this._compileSchemaEnv(sch);
        }
        // Remove cached schema(s).
        // If no parameter is passed all schemas but meta-schemas are removed.
        // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
        // Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
        removeSchema(schemaKeyRef) {
          if (schemaKeyRef instanceof RegExp) {
            this._removeAllSchemas(this.schemas, schemaKeyRef);
            this._removeAllSchemas(this.refs, schemaKeyRef);
            return this;
          }
          switch (typeof schemaKeyRef) {
            case "undefined":
              this._removeAllSchemas(this.schemas);
              this._removeAllSchemas(this.refs);
              this._cache.clear();
              return this;
            case "string": {
              const sch = getSchEnv.call(this, schemaKeyRef);
              if (typeof sch == "object")
                this._cache.delete(sch.schema);
              delete this.schemas[schemaKeyRef];
              delete this.refs[schemaKeyRef];
              return this;
            }
            case "object": {
              const cacheKey = schemaKeyRef;
              this._cache.delete(cacheKey);
              let id2 = schemaKeyRef[this.opts.schemaId];
              if (id2) {
                id2 = (0, resolve_1.normalizeId)(id2);
                delete this.schemas[id2];
                delete this.refs[id2];
              }
              return this;
            }
            default:
              throw new Error("ajv.removeSchema: invalid parameter");
          }
        }
        // add "vocabulary" - a collection of keywords
        addVocabulary(definitions2) {
          for (const def of definitions2)
            this.addKeyword(def);
          return this;
        }
        addKeyword(kwdOrDef, def) {
          let keyword2;
          if (typeof kwdOrDef == "string") {
            keyword2 = kwdOrDef;
            if (typeof def == "object") {
              this.logger.warn("these parameters are deprecated, see docs for addKeyword");
              def.keyword = keyword2;
            }
          } else if (typeof kwdOrDef == "object" && def === void 0) {
            def = kwdOrDef;
            keyword2 = def.keyword;
            if (Array.isArray(keyword2) && !keyword2.length) {
              throw new Error("addKeywords: keyword must be string or non-empty array");
            }
          } else {
            throw new Error("invalid addKeywords parameters");
          }
          checkKeyword.call(this, keyword2, def);
          if (!def) {
            (0, util_1.eachItem)(keyword2, (kwd) => addRule.call(this, kwd));
            return this;
          }
          keywordMetaschema.call(this, def);
          const definition2 = __spreadProps(__spreadValues({}, def), {
            type: (0, dataType_1.getJSONTypes)(def.type),
            schemaType: (0, dataType_1.getJSONTypes)(def.schemaType)
          });
          (0, util_1.eachItem)(keyword2, definition2.type.length === 0 ? (k) => addRule.call(this, k, definition2) : (k) => definition2.type.forEach((t) => addRule.call(this, k, definition2, t)));
          return this;
        }
        getKeyword(keyword2) {
          const rule = this.RULES.all[keyword2];
          return typeof rule == "object" ? rule.definition : !!rule;
        }
        // Remove keyword
        removeKeyword(keyword2) {
          const { RULES } = this;
          delete RULES.keywords[keyword2];
          delete RULES.all[keyword2];
          for (const group of RULES.rules) {
            const i2 = group.rules.findIndex((rule) => rule.keyword === keyword2);
            if (i2 >= 0)
              group.rules.splice(i2, 1);
          }
          return this;
        }
        // Add format
        addFormat(name2, format2) {
          if (typeof format2 == "string")
            format2 = new RegExp(format2);
          this.formats[name2] = format2;
          return this;
        }
        errorsText(errors2 = this.errors, { separator = ", ", dataVar = "data" } = {}) {
          if (!errors2 || errors2.length === 0)
            return "No errors";
          return errors2.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text, msg) => text + separator + msg);
        }
        $dataMetaSchema(metaSchema, keywordsJsonPointers) {
          const rules2 = this.RULES.all;
          metaSchema = JSON.parse(JSON.stringify(metaSchema));
          for (const jsonPointer of keywordsJsonPointers) {
            const segments = jsonPointer.split("/").slice(1);
            let keywords = metaSchema;
            for (const seg of segments)
              keywords = keywords[seg];
            for (const key in rules2) {
              const rule = rules2[key];
              if (typeof rule != "object")
                continue;
              const { $data } = rule.definition;
              const schema = keywords[key];
              if ($data && schema)
                keywords[key] = schemaOrData(schema);
            }
          }
          return metaSchema;
        }
        _removeAllSchemas(schemas, regex) {
          for (const keyRef in schemas) {
            const sch = schemas[keyRef];
            if (!regex || regex.test(keyRef)) {
              if (typeof sch == "string") {
                delete schemas[keyRef];
              } else if (sch && !sch.meta) {
                this._cache.delete(sch.schema);
                delete schemas[keyRef];
              }
            }
          }
        }
        _addSchema(schema, meta2, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {
          let id2;
          const { schemaId } = this.opts;
          if (typeof schema == "object") {
            id2 = schema[schemaId];
          } else {
            if (this.opts.jtd)
              throw new Error("schema must be object");
            else if (typeof schema != "boolean")
              throw new Error("schema must be object or boolean");
          }
          let sch = this._cache.get(schema);
          if (sch !== void 0)
            return sch;
          baseId = (0, resolve_1.normalizeId)(id2 || baseId);
          const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId);
          sch = new compile_1.SchemaEnv({ schema, schemaId, meta: meta2, baseId, localRefs });
          this._cache.set(sch.schema, sch);
          if (addSchema && !baseId.startsWith("#")) {
            if (baseId)
              this._checkUnique(baseId);
            this.refs[baseId] = sch;
          }
          if (validateSchema)
            this.validateSchema(schema, true);
          return sch;
        }
        _checkUnique(id2) {
          if (this.schemas[id2] || this.refs[id2]) {
            throw new Error(`schema with key or id "${id2}" already exists`);
          }
        }
        _compileSchemaEnv(sch) {
          if (sch.meta)
            this._compileMetaSchema(sch);
          else
            compile_1.compileSchema.call(this, sch);
          if (!sch.validate)
            throw new Error("ajv implementation error");
          return sch.validate;
        }
        _compileMetaSchema(sch) {
          const currentOpts = this.opts;
          this.opts = this._metaOpts;
          try {
            compile_1.compileSchema.call(this, sch);
          } finally {
            this.opts = currentOpts;
          }
        }
      }
      Ajv2.ValidationError = validation_error_1.default;
      Ajv2.MissingRefError = ref_error_1.default;
      exports$12.default = Ajv2;
      function checkOptions(checkOpts, options, msg, log = "error") {
        for (const key in checkOpts) {
          const opt = key;
          if (opt in options)
            this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);
        }
      }
      function getSchEnv(keyRef) {
        keyRef = (0, resolve_1.normalizeId)(keyRef);
        return this.schemas[keyRef] || this.refs[keyRef];
      }
      function addInitialSchemas() {
        const optsSchemas = this.opts.schemas;
        if (!optsSchemas)
          return;
        if (Array.isArray(optsSchemas))
          this.addSchema(optsSchemas);
        else
          for (const key in optsSchemas)
            this.addSchema(optsSchemas[key], key);
      }
      function addInitialFormats() {
        for (const name2 in this.opts.formats) {
          const format2 = this.opts.formats[name2];
          if (format2)
            this.addFormat(name2, format2);
        }
      }
      function addInitialKeywords(defs) {
        if (Array.isArray(defs)) {
          this.addVocabulary(defs);
          return;
        }
        this.logger.warn("keywords option as map is deprecated, pass array");
        for (const keyword2 in defs) {
          const def = defs[keyword2];
          if (!def.keyword)
            def.keyword = keyword2;
          this.addKeyword(def);
        }
      }
      function getMetaSchemaOptions() {
        const metaOpts = __spreadValues({}, this.opts);
        for (const opt of META_IGNORE_OPTIONS)
          delete metaOpts[opt];
        return metaOpts;
      }
      const noLogs = { log() {
      }, warn() {
      }, error() {
      } };
      function getLogger(logger2) {
        if (logger2 === false)
          return noLogs;
        if (logger2 === void 0)
          return console;
        if (logger2.log && logger2.warn && logger2.error)
          return logger2;
        throw new Error("logger must implement log, warn and error methods");
      }
      const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;
      function checkKeyword(keyword2, def) {
        const { RULES } = this;
        (0, util_1.eachItem)(keyword2, (kwd) => {
          if (RULES.keywords[kwd])
            throw new Error(`Keyword ${kwd} is already defined`);
          if (!KEYWORD_NAME.test(kwd))
            throw new Error(`Keyword ${kwd} has invalid name`);
        });
        if (!def)
          return;
        if (def.$data && !("code" in def || "validate" in def)) {
          throw new Error('$data keyword must have "code" or "validate" function');
        }
      }
      function addRule(keyword2, definition2, dataType2) {
        var _a3;
        const post = definition2 === null || definition2 === void 0 ? void 0 : definition2.post;
        if (dataType2 && post)
          throw new Error('keyword with "post" flag cannot have "type"');
        const { RULES } = this;
        let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType2);
        if (!ruleGroup) {
          ruleGroup = { type: dataType2, rules: [] };
          RULES.rules.push(ruleGroup);
        }
        RULES.keywords[keyword2] = true;
        if (!definition2)
          return;
        const rule = {
          keyword: keyword2,
          definition: __spreadProps(__spreadValues({}, definition2), {
            type: (0, dataType_1.getJSONTypes)(definition2.type),
            schemaType: (0, dataType_1.getJSONTypes)(definition2.schemaType)
          })
        };
        if (definition2.before)
          addBeforeRule.call(this, ruleGroup, rule, definition2.before);
        else
          ruleGroup.rules.push(rule);
        RULES.all[keyword2] = rule;
        (_a3 = definition2.implements) === null || _a3 === void 0 ? void 0 : _a3.forEach((kwd) => this.addKeyword(kwd));
      }
      function addBeforeRule(ruleGroup, rule, before) {
        const i2 = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
        if (i2 >= 0) {
          ruleGroup.rules.splice(i2, 0, rule);
        } else {
          ruleGroup.rules.push(rule);
          this.logger.warn(`rule ${before} is not defined`);
        }
      }
      function keywordMetaschema(def) {
        let { metaSchema } = def;
        if (metaSchema === void 0)
          return;
        if (def.$data && this.opts.$data)
          metaSchema = schemaOrData(metaSchema);
        def.validateSchema = this.compile(metaSchema, true);
      }
      const $dataRef = {
        $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"
      };
      function schemaOrData(schema) {
        return { anyOf: [schema, $dataRef] };
      }
    })(core$1);
    return core$1;
  }
  var draft7 = {};
  var core = {};
  var id = {};
  var hasRequiredId;
  function requireId() {
    if (hasRequiredId) return id;
    hasRequiredId = 1;
    Object.defineProperty(id, "__esModule", { value: true });
    const def = {
      keyword: "id",
      code() {
        throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID');
      }
    };
    id.default = def;
    return id;
  }
  var ref = {};
  var hasRequiredRef;
  function requireRef() {
    if (hasRequiredRef) return ref;
    hasRequiredRef = 1;
    Object.defineProperty(ref, "__esModule", { value: true });
    ref.callRef = ref.getValidate = void 0;
    const ref_error_1 = requireRef_error();
    const code_1 = requireCode();
    const codegen_1 = requireCodegen();
    const names_1 = requireNames();
    const compile_1 = requireCompile();
    const util_1 = requireUtil();
    const def = {
      keyword: "$ref",
      schemaType: "string",
      code(cxt) {
        const { gen, schema: $ref, it: it2 } = cxt;
        const { baseId, schemaEnv: env2, validateName, opts, self: self2 } = it2;
        const { root } = env2;
        if (($ref === "#" || $ref === "#/") && baseId === root.baseId)
          return callRootRef();
        const schOrEnv = compile_1.resolveRef.call(self2, root, baseId, $ref);
        if (schOrEnv === void 0)
          throw new ref_error_1.default(it2.opts.uriResolver, baseId, $ref);
        if (schOrEnv instanceof compile_1.SchemaEnv)
          return callValidate(schOrEnv);
        return inlineRefSchema(schOrEnv);
        function callRootRef() {
          if (env2 === root)
            return callRef(cxt, validateName, env2, env2.$async);
          const rootName = gen.scopeValue("root", { ref: root });
          return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async);
        }
        function callValidate(sch) {
          const v = getValidate(cxt, sch);
          callRef(cxt, v, sch, sch.$async);
        }
        function inlineRefSchema(sch) {
          const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch });
          const valid = gen.name("valid");
          const schCxt = cxt.subschema({
            schema: sch,
            dataTypes: [],
            schemaPath: codegen_1.nil,
            topSchemaRef: schName,
            errSchemaPath: $ref
          }, valid);
          cxt.mergeEvaluated(schCxt);
          cxt.ok(valid);
        }
      }
    };
    function getValidate(cxt, sch) {
      const { gen } = cxt;
      return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`;
    }
    ref.getValidate = getValidate;
    function callRef(cxt, v, sch, $async) {
      const { gen, it: it2 } = cxt;
      const { allErrors, schemaEnv: env2, opts } = it2;
      const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil;
      if ($async)
        callAsyncRef();
      else
        callSyncRef();
      function callAsyncRef() {
        if (!env2.$async)
          throw new Error("async schema referenced by sync schema");
        const valid = gen.let("valid");
        gen.try(() => {
          gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`);
          addEvaluatedFrom(v);
          if (!allErrors)
            gen.assign(valid, true);
        }, (e) => {
          gen.if((0, codegen_1._)`!(${e} instanceof ${it2.ValidationError})`, () => gen.throw(e));
          addErrorsFrom(e);
          if (!allErrors)
            gen.assign(valid, false);
        });
        cxt.ok(valid);
      }
      function callSyncRef() {
        cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v));
      }
      function addErrorsFrom(source) {
        const errs = (0, codegen_1._)`${source}.errors`;
        gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`);
        gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`);
      }
      function addEvaluatedFrom(source) {
        var _a3;
        if (!it2.opts.unevaluated)
          return;
        const schEvaluated = (_a3 = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a3 === void 0 ? void 0 : _a3.evaluated;
        if (it2.props !== true) {
          if (schEvaluated && !schEvaluated.dynamicProps) {
            if (schEvaluated.props !== void 0) {
              it2.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it2.props);
            }
          } else {
            const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`);
            it2.props = util_1.mergeEvaluated.props(gen, props, it2.props, codegen_1.Name);
          }
        }
        if (it2.items !== true) {
          if (schEvaluated && !schEvaluated.dynamicItems) {
            if (schEvaluated.items !== void 0) {
              it2.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it2.items);
            }
          } else {
            const items2 = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`);
            it2.items = util_1.mergeEvaluated.items(gen, items2, it2.items, codegen_1.Name);
          }
        }
      }
    }
    ref.callRef = callRef;
    ref.default = def;
    return ref;
  }
  var hasRequiredCore;
  function requireCore() {
    if (hasRequiredCore) return core;
    hasRequiredCore = 1;
    Object.defineProperty(core, "__esModule", { value: true });
    const id_1 = requireId();
    const ref_1 = requireRef();
    const core$12 = [
      "$schema",
      "$id",
      "$defs",
      "$vocabulary",
      { keyword: "$comment" },
      "definitions",
      id_1.default,
      ref_1.default
    ];
    core.default = core$12;
    return core;
  }
  var validation = {};
  var limitNumber = {};
  var hasRequiredLimitNumber;
  function requireLimitNumber() {
    if (hasRequiredLimitNumber) return limitNumber;
    hasRequiredLimitNumber = 1;
    Object.defineProperty(limitNumber, "__esModule", { value: true });
    const codegen_1 = requireCodegen();
    const ops = codegen_1.operators;
    const KWDs = {
      maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT },
      minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT },
      exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE },
      exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE }
    };
    const error2 = {
      message: ({ keyword: keyword2, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword2].okStr} ${schemaCode}`,
      params: ({ keyword: keyword2, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword2].okStr}, limit: ${schemaCode}}`
    };
    const def = {
      keyword: Object.keys(KWDs),
      type: "number",
      schemaType: "number",
      $data: true,
      error: error2,
      code(cxt) {
        const { keyword: keyword2, data, schemaCode } = cxt;
        cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword2].fail} ${schemaCode} || isNaN(${data})`);
      }
    };
    limitNumber.default = def;
    return limitNumber;
  }
  var multipleOf = {};
  var hasRequiredMultipleOf;
  function requireMultipleOf() {
    if (hasRequiredMultipleOf) return multipleOf;
    hasRequiredMultipleOf = 1;
    Object.defineProperty(multipleOf, "__esModule", { value: true });
    const codegen_1 = requireCodegen();
    const error2 = {
      message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`,
      params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}`
    };
    const def = {
      keyword: "multipleOf",
      type: "number",
      schemaType: "number",
      $data: true,
      error: error2,
      code(cxt) {
        const { gen, data, schemaCode, it: it2 } = cxt;
        const prec = it2.opts.multipleOfPrecision;
        const res = gen.let("res");
        const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`;
        cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`);
      }
    };
    multipleOf.default = def;
    return multipleOf;
  }
  var limitLength = {};
  var ucs2length = {};
  var hasRequiredUcs2length;
  function requireUcs2length() {
    if (hasRequiredUcs2length) return ucs2length;
    hasRequiredUcs2length = 1;
    Object.defineProperty(ucs2length, "__esModule", { value: true });
    function ucs2length$1(str) {
      const len2 = str.length;
      let length = 0;
      let pos = 0;
      let value;
      while (pos < len2) {
        length++;
        value = str.charCodeAt(pos++);
        if (value >= 55296 && value <= 56319 && pos < len2) {
          value = str.charCodeAt(pos);
          if ((value & 64512) === 56320)
            pos++;
        }
      }
      return length;
    }
    ucs2length.default = ucs2length$1;
    ucs2length$1.code = 'require("ajv/dist/runtime/ucs2length").default';
    return ucs2length;
  }
  var hasRequiredLimitLength;
  function requireLimitLength() {
    if (hasRequiredLimitLength) return limitLength;
    hasRequiredLimitLength = 1;
    Object.defineProperty(limitLength, "__esModule", { value: true });
    const codegen_1 = requireCodegen();
    const util_1 = requireUtil();
    const ucs2length_1 = requireUcs2length();
    const error2 = {
      message({ keyword: keyword2, schemaCode }) {
        const comp = keyword2 === "maxLength" ? "more" : "fewer";
        return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`;
      },
      params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`
    };
    const def = {
      keyword: ["maxLength", "minLength"],
      type: "string",
      schemaType: "number",
      $data: true,
      error: error2,
      code(cxt) {
        const { keyword: keyword2, data, schemaCode, it: it2 } = cxt;
        const op = keyword2 === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT;
        const len2 = it2.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`;
        cxt.fail$data((0, codegen_1._)`${len2} ${op} ${schemaCode}`);
      }
    };
    limitLength.default = def;
    return limitLength;
  }
  var pattern = {};
  var hasRequiredPattern;
  function requirePattern() {
    if (hasRequiredPattern) return pattern;
    hasRequiredPattern = 1;
    Object.defineProperty(pattern, "__esModule", { value: true });
    const code_1 = requireCode();
    const codegen_1 = requireCodegen();
    const error2 = {
      message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`,
      params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}`
    };
    const def = {
      keyword: "pattern",
      type: "string",
      schemaType: "string",
      $data: true,
      error: error2,
      code(cxt) {
        const { data, $data, schema, schemaCode, it: it2 } = cxt;
        const u = it2.opts.unicodeRegExp ? "u" : "";
        const regExp = $data ? (0, codegen_1._)`(new RegExp(${schemaCode}, ${u}))` : (0, code_1.usePattern)(cxt, schema);
        cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`);
      }
    };
    pattern.default = def;
    return pattern;
  }
  var limitProperties = {};
  var hasRequiredLimitProperties;
  function requireLimitProperties() {
    if (hasRequiredLimitProperties) return limitProperties;
    hasRequiredLimitProperties = 1;
    Object.defineProperty(limitProperties, "__esModule", { value: true });
    const codegen_1 = requireCodegen();
    const error2 = {
      message({ keyword: keyword2, schemaCode }) {
        const comp = keyword2 === "maxProperties" ? "more" : "fewer";
        return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`;
      },
      params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`
    };
    const def = {
      keyword: ["maxProperties", "minProperties"],
      type: "object",
      schemaType: "number",
      $data: true,
      error: error2,
      code(cxt) {
        const { keyword: keyword2, data, schemaCode } = cxt;
        const op = keyword2 === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT;
        cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`);
      }
    };
    limitProperties.default = def;
    return limitProperties;
  }
  var required = {};
  var hasRequiredRequired;
  function requireRequired() {
    if (hasRequiredRequired) return required;
    hasRequiredRequired = 1;
    Object.defineProperty(required, "__esModule", { value: true });
    const code_1 = requireCode();
    const codegen_1 = requireCodegen();
    const util_1 = requireUtil();
    const error2 = {
      message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`,
      params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}`
    };
    const def = {
      keyword: "required",
      type: "object",
      schemaType: "array",
      $data: true,
      error: error2,
      code(cxt) {
        const { gen, schema, schemaCode, data, $data, it: it2 } = cxt;
        const { opts } = it2;
        if (!$data && schema.length === 0)
          return;
        const useLoop = schema.length >= opts.loopRequired;
        if (it2.allErrors)
          allErrorsMode();
        else
          exitOnErrorMode();
        if (opts.strictRequired) {
          const props = cxt.parentSchema.properties;
          const { definedProperties } = cxt.it;
          for (const requiredKey of schema) {
            if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) {
              const schemaPath = it2.schemaEnv.baseId + it2.errSchemaPath;
              const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`;
              (0, util_1.checkStrictMode)(it2, msg, it2.opts.strictRequired);
            }
          }
        }
        function allErrorsMode() {
          if (useLoop || $data) {
            cxt.block$data(codegen_1.nil, loopAllRequired);
          } else {
            for (const prop of schema) {
              (0, code_1.checkReportMissingProp)(cxt, prop);
            }
          }
        }
        function exitOnErrorMode() {
          const missing = gen.let("missing");
          if (useLoop || $data) {
            const valid = gen.let("valid", true);
            cxt.block$data(valid, () => loopUntilMissing(missing, valid));
            cxt.ok(valid);
          } else {
            gen.if((0, code_1.checkMissingProp)(cxt, schema, missing));
            (0, code_1.reportMissingProp)(cxt, missing);
            gen.else();
          }
        }
        function loopAllRequired() {
          gen.forOf("prop", schemaCode, (prop) => {
            cxt.setParams({ missingProperty: prop });
            gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error());
          });
        }
        function loopUntilMissing(missing, valid) {
          cxt.setParams({ missingProperty: missing });
          gen.forOf(missing, schemaCode, () => {
            gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties));
            gen.if((0, codegen_1.not)(valid), () => {
              cxt.error();
              gen.break();
            });
          }, codegen_1.nil);
        }
      }
    };
    required.default = def;
    return required;
  }
  var limitItems = {};
  var hasRequiredLimitItems;
  function requireLimitItems() {
    if (hasRequiredLimitItems) return limitItems;
    hasRequiredLimitItems = 1;
    Object.defineProperty(limitItems, "__esModule", { value: true });
    const codegen_1 = requireCodegen();
    const error2 = {
      message({ keyword: keyword2, schemaCode }) {
        const comp = keyword2 === "maxItems" ? "more" : "fewer";
        return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`;
      },
      params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`
    };
    const def = {
      keyword: ["maxItems", "minItems"],
      type: "array",
      schemaType: "number",
      $data: true,
      error: error2,
      code(cxt) {
        const { keyword: keyword2, data, schemaCode } = cxt;
        const op = keyword2 === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT;
        cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`);
      }
    };
    limitItems.default = def;
    return limitItems;
  }
  var uniqueItems = {};
  var equal = {};
  var hasRequiredEqual;
  function requireEqual() {
    if (hasRequiredEqual) return equal;
    hasRequiredEqual = 1;
    Object.defineProperty(equal, "__esModule", { value: true });
    const equal$1 = requireFastDeepEqual();
    equal$1.code = 'require("ajv/dist/runtime/equal").default';
    equal.default = equal$1;
    return equal;
  }
  var hasRequiredUniqueItems;
  function requireUniqueItems() {
    if (hasRequiredUniqueItems) return uniqueItems;
    hasRequiredUniqueItems = 1;
    Object.defineProperty(uniqueItems, "__esModule", { value: true });
    const dataType_1 = requireDataType();
    const codegen_1 = requireCodegen();
    const util_1 = requireUtil();
    const equal_1 = requireEqual();
    const error2 = {
      message: ({ params: { i: i2, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i2} are identical)`,
      params: ({ params: { i: i2, j } }) => (0, codegen_1._)`{i: ${i2}, j: ${j}}`
    };
    const def = {
      keyword: "uniqueItems",
      type: "array",
      schemaType: "boolean",
      $data: true,
      error: error2,
      code(cxt) {
        const { gen, data, $data, schema, parentSchema, schemaCode, it: it2 } = cxt;
        if (!$data && !schema)
          return;
        const valid = gen.let("valid");
        const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : [];
        cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`);
        cxt.ok(valid);
        function validateUniqueItems() {
          const i2 = gen.let("i", (0, codegen_1._)`${data}.length`);
          const j = gen.let("j");
          cxt.setParams({ i: i2, j });
          gen.assign(valid, true);
          gen.if((0, codegen_1._)`${i2} > 1`, () => (canOptimize() ? loopN : loopN2)(i2, j));
        }
        function canOptimize() {
          return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array");
        }
        function loopN(i2, j) {
          const item = gen.name("item");
          const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it2.opts.strictNumbers, dataType_1.DataType.Wrong);
          const indices = gen.const("indices", (0, codegen_1._)`{}`);
          gen.for((0, codegen_1._)`;${i2}--;`, () => {
            gen.let(item, (0, codegen_1._)`${data}[${i2}]`);
            gen.if(wrongType, (0, codegen_1._)`continue`);
            if (itemTypes.length > 1)
              gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`);
            gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => {
              gen.assign(j, (0, codegen_1._)`${indices}[${item}]`);
              cxt.error();
              gen.assign(valid, false).break();
            }).code((0, codegen_1._)`${indices}[${item}] = ${i2}`);
          });
        }
        function loopN2(i2, j) {
          const eql = (0, util_1.useFunc)(gen, equal_1.default);
          const outer = gen.name("outer");
          gen.label(outer).for((0, codegen_1._)`;${i2}--;`, () => gen.for((0, codegen_1._)`${j} = ${i2}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i2}], ${data}[${j}])`, () => {
            cxt.error();
            gen.assign(valid, false).break(outer);
          })));
        }
      }
    };
    uniqueItems.default = def;
    return uniqueItems;
  }
  var _const = {};
  var hasRequired_const;
  function require_const() {
    if (hasRequired_const) return _const;
    hasRequired_const = 1;
    Object.defineProperty(_const, "__esModule", { value: true });
    const codegen_1 = requireCodegen();
    const util_1 = requireUtil();
    const equal_1 = requireEqual();
    const error2 = {
      message: "must be equal to constant",
      params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}`
    };
    const def = {
      keyword: "const",
      $data: true,
      error: error2,
      code(cxt) {
        const { gen, data, $data, schemaCode, schema } = cxt;
        if ($data || schema && typeof schema == "object") {
          cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`);
        } else {
          cxt.fail((0, codegen_1._)`${schema} !== ${data}`);
        }
      }
    };
    _const.default = def;
    return _const;
  }
  var _enum = {};
  var hasRequired_enum;
  function require_enum() {
    if (hasRequired_enum) return _enum;
    hasRequired_enum = 1;
    Object.defineProperty(_enum, "__esModule", { value: true });
    const codegen_1 = requireCodegen();
    const util_1 = requireUtil();
    const equal_1 = requireEqual();
    const error2 = {
      message: "must be equal to one of the allowed values",
      params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}`
    };
    const def = {
      keyword: "enum",
      schemaType: "array",
      $data: true,
      error: error2,
      code(cxt) {
        const { gen, data, $data, schema, schemaCode, it: it2 } = cxt;
        if (!$data && schema.length === 0)
          throw new Error("enum must have non-empty array");
        const useLoop = schema.length >= it2.opts.loopEnum;
        let eql;
        const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default);
        let valid;
        if (useLoop || $data) {
          valid = gen.let("valid");
          cxt.block$data(valid, loopEnum);
        } else {
          if (!Array.isArray(schema))
            throw new Error("ajv implementation error");
          const vSchema = gen.const("vSchema", schemaCode);
          valid = (0, codegen_1.or)(...schema.map((_x, i2) => equalCode(vSchema, i2)));
        }
        cxt.pass(valid);
        function loopEnum() {
          gen.assign(valid, false);
          gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break()));
        }
        function equalCode(vSchema, i2) {
          const sch = schema[i2];
          return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i2}])` : (0, codegen_1._)`${data} === ${sch}`;
        }
      }
    };
    _enum.default = def;
    return _enum;
  }
  var hasRequiredValidation;
  function requireValidation() {
    if (hasRequiredValidation) return validation;
    hasRequiredValidation = 1;
    Object.defineProperty(validation, "__esModule", { value: true });
    const limitNumber_1 = requireLimitNumber();
    const multipleOf_1 = requireMultipleOf();
    const limitLength_1 = requireLimitLength();
    const pattern_1 = requirePattern();
    const limitProperties_1 = requireLimitProperties();
    const required_1 = requireRequired();
    const limitItems_1 = requireLimitItems();
    const uniqueItems_1 = requireUniqueItems();
    const const_1 = require_const();
    const enum_1 = require_enum();
    const validation$1 = [
      // number
      limitNumber_1.default,
      multipleOf_1.default,
      // string
      limitLength_1.default,
      pattern_1.default,
      // object
      limitProperties_1.default,
      required_1.default,
      // array
      limitItems_1.default,
      uniqueItems_1.default,
      // any
      { keyword: "type", schemaType: ["string", "array"] },
      { keyword: "nullable", schemaType: "boolean" },
      const_1.default,
      enum_1.default
    ];
    validation.default = validation$1;
    return validation;
  }
  var applicator = {};
  var additionalItems = {};
  var hasRequiredAdditionalItems;
  function requireAdditionalItems() {
    if (hasRequiredAdditionalItems) return additionalItems;
    hasRequiredAdditionalItems = 1;
    Object.defineProperty(additionalItems, "__esModule", { value: true });
    additionalItems.validateAdditionalItems = void 0;
    const codegen_1 = requireCodegen();
    const util_1 = requireUtil();
    const error2 = {
      message: ({ params: { len: len2 } }) => (0, codegen_1.str)`must NOT have more than ${len2} items`,
      params: ({ params: { len: len2 } }) => (0, codegen_1._)`{limit: ${len2}}`
    };
    const def = {
      keyword: "additionalItems",
      type: "array",
      schemaType: ["boolean", "object"],
      before: "uniqueItems",
      error: error2,
      code(cxt) {
        const { parentSchema, it: it2 } = cxt;
        const { items: items2 } = parentSchema;
        if (!Array.isArray(items2)) {
          (0, util_1.checkStrictMode)(it2, '"additionalItems" is ignored when "items" is not an array of schemas');
          return;
        }
        validateAdditionalItems(cxt, items2);
      }
    };
    function validateAdditionalItems(cxt, items2) {
      const { gen, schema, data, keyword: keyword2, it: it2 } = cxt;
      it2.items = true;
      const len2 = gen.const("len", (0, codegen_1._)`${data}.length`);
      if (schema === false) {
        cxt.setParams({ len: items2.length });
        cxt.pass((0, codegen_1._)`${len2} <= ${items2.length}`);
      } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it2, schema)) {
        const valid = gen.var("valid", (0, codegen_1._)`${len2} <= ${items2.length}`);
        gen.if((0, codegen_1.not)(valid), () => validateItems(valid));
        cxt.ok(valid);
      }
      function validateItems(valid) {
        gen.forRange("i", items2.length, len2, (i2) => {
          cxt.subschema({ keyword: keyword2, dataProp: i2, dataPropType: util_1.Type.Num }, valid);
          if (!it2.allErrors)
            gen.if((0, codegen_1.not)(valid), () => gen.break());
        });
      }
    }
    additionalItems.validateAdditionalItems = validateAdditionalItems;
    additionalItems.default = def;
    return additionalItems;
  }
  var prefixItems = {};
  var items = {};
  var hasRequiredItems;
  function requireItems() {
    if (hasRequiredItems) return items;
    hasRequiredItems = 1;
    Object.defineProperty(items, "__esModule", { value: true });
    items.validateTuple = void 0;
    const codegen_1 = requireCodegen();
    const util_1 = requireUtil();
    const code_1 = requireCode();
    const def = {
      keyword: "items",
      type: "array",
      schemaType: ["object", "array", "boolean"],
      before: "uniqueItems",
      code(cxt) {
        const { schema, it: it2 } = cxt;
        if (Array.isArray(schema))
          return validateTuple(cxt, "additionalItems", schema);
        it2.items = true;
        if ((0, util_1.alwaysValidSchema)(it2, schema))
          return;
        cxt.ok((0, code_1.validateArray)(cxt));
      }
    };
    function validateTuple(cxt, extraItems, schArr = cxt.schema) {
      const { gen, parentSchema, data, keyword: keyword2, it: it2 } = cxt;
      checkStrictTuple(parentSchema);
      if (it2.opts.unevaluated && schArr.length && it2.items !== true) {
        it2.items = util_1.mergeEvaluated.items(gen, schArr.length, it2.items);
      }
      const valid = gen.name("valid");
      const len2 = gen.const("len", (0, codegen_1._)`${data}.length`);
      schArr.forEach((sch, i2) => {
        if ((0, util_1.alwaysValidSchema)(it2, sch))
          return;
        gen.if((0, codegen_1._)`${len2} > ${i2}`, () => cxt.subschema({
          keyword: keyword2,
          schemaProp: i2,
          dataProp: i2
        }, valid));
        cxt.ok(valid);
      });
      function checkStrictTuple(sch) {
        const { opts, errSchemaPath } = it2;
        const l = schArr.length;
        const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false);
        if (opts.strictTuples && !fullTuple) {
          const msg = `"${keyword2}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`;
          (0, util_1.checkStrictMode)(it2, msg, opts.strictTuples);
        }
      }
    }
    items.validateTuple = validateTuple;
    items.default = def;
    return items;
  }
  var hasRequiredPrefixItems;
  function requirePrefixItems() {
    if (hasRequiredPrefixItems) return prefixItems;
    hasRequiredPrefixItems = 1;
    Object.defineProperty(prefixItems, "__esModule", { value: true });
    const items_1 = requireItems();
    const def = {
      keyword: "prefixItems",
      type: "array",
      schemaType: ["array"],
      before: "uniqueItems",
      code: (cxt) => (0, items_1.validateTuple)(cxt, "items")
    };
    prefixItems.default = def;
    return prefixItems;
  }
  var items2020 = {};
  var hasRequiredItems2020;
  function requireItems2020() {
    if (hasRequiredItems2020) return items2020;
    hasRequiredItems2020 = 1;
    Object.defineProperty(items2020, "__esModule", { value: true });
    const codegen_1 = requireCodegen();
    const util_1 = requireUtil();
    const code_1 = requireCode();
    const additionalItems_1 = requireAdditionalItems();
    const error2 = {
      message: ({ params: { len: len2 } }) => (0, codegen_1.str)`must NOT have more than ${len2} items`,
      params: ({ params: { len: len2 } }) => (0, codegen_1._)`{limit: ${len2}}`
    };
    const def = {
      keyword: "items",
      type: "array",
      schemaType: ["object", "boolean"],
      before: "uniqueItems",
      error: error2,
      code(cxt) {
        const { schema, parentSchema, it: it2 } = cxt;
        const { prefixItems: prefixItems2 } = parentSchema;
        it2.items = true;
        if ((0, util_1.alwaysValidSchema)(it2, schema))
          return;
        if (prefixItems2)
          (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems2);
        else
          cxt.ok((0, code_1.validateArray)(cxt));
      }
    };
    items2020.default = def;
    return items2020;
  }
  var contains = {};
  var hasRequiredContains;
  function requireContains() {
    if (hasRequiredContains) return contains;
    hasRequiredContains = 1;
    Object.defineProperty(contains, "__esModule", { value: true });
    const codegen_1 = requireCodegen();
    const util_1 = requireUtil();
    const error2 = {
      message: ({ params: { min, max: max2 } }) => max2 === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max2} valid item(s)`,
      params: ({ params: { min, max: max2 } }) => max2 === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max2}}`
    };
    const def = {
      keyword: "contains",
      type: "array",
      schemaType: ["object", "boolean"],
      before: "uniqueItems",
      trackErrors: true,
      error: error2,
      code(cxt) {
        const { gen, schema, parentSchema, data, it: it2 } = cxt;
        let min;
        let max2;
        const { minContains, maxContains } = parentSchema;
        if (it2.opts.next) {
          min = minContains === void 0 ? 1 : minContains;
          max2 = maxContains;
        } else {
          min = 1;
        }
        const len2 = gen.const("len", (0, codegen_1._)`${data}.length`);
        cxt.setParams({ min, max: max2 });
        if (max2 === void 0 && min === 0) {
          (0, util_1.checkStrictMode)(it2, `"minContains" == 0 without "maxContains": "contains" keyword ignored`);
          return;
        }
        if (max2 !== void 0 && min > max2) {
          (0, util_1.checkStrictMode)(it2, `"minContains" > "maxContains" is always invalid`);
          cxt.fail();
          return;
        }
        if ((0, util_1.alwaysValidSchema)(it2, schema)) {
          let cond = (0, codegen_1._)`${len2} >= ${min}`;
          if (max2 !== void 0)
            cond = (0, codegen_1._)`${cond} && ${len2} <= ${max2}`;
          cxt.pass(cond);
          return;
        }
        it2.items = true;
        const valid = gen.name("valid");
        if (max2 === void 0 && min === 1) {
          validateItems(valid, () => gen.if(valid, () => gen.break()));
        } else if (min === 0) {
          gen.let(valid, true);
          if (max2 !== void 0)
            gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount);
        } else {
          gen.let(valid, false);
          validateItemsWithCount();
        }
        cxt.result(valid, () => cxt.reset());
        function validateItemsWithCount() {
          const schValid = gen.name("_valid");
          const count = gen.let("count", 0);
          validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)));
        }
        function validateItems(_valid, block) {
          gen.forRange("i", 0, len2, (i2) => {
            cxt.subschema({
              keyword: "contains",
              dataProp: i2,
              dataPropType: util_1.Type.Num,
              compositeRule: true
            }, _valid);
            block();
          });
        }
        function checkLimits(count) {
          gen.code((0, codegen_1._)`${count}++`);
          if (max2 === void 0) {
            gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break());
          } else {
            gen.if((0, codegen_1._)`${count} > ${max2}`, () => gen.assign(valid, false).break());
            if (min === 1)
              gen.assign(valid, true);
            else
              gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true));
          }
        }
      }
    };
    contains.default = def;
    return contains;
  }
  var dependencies = {};
  var hasRequiredDependencies;
  function requireDependencies() {
    if (hasRequiredDependencies) return dependencies;
    hasRequiredDependencies = 1;
    (function(exports$12) {
      Object.defineProperty(exports$12, "__esModule", { value: true });
      exports$12.validateSchemaDeps = exports$12.validatePropertyDeps = exports$12.error = void 0;
      const codegen_1 = requireCodegen();
      const util_1 = requireUtil();
      const code_1 = requireCode();
      exports$12.error = {
        message: ({ params: { property, depsCount, deps } }) => {
          const property_ies = depsCount === 1 ? "property" : "properties";
          return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`;
        },
        params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property},
    missingProperty: ${missingProperty},
    depsCount: ${depsCount},
    deps: ${deps}}`
        // TODO change to reference
      };
      const def = {
        keyword: "dependencies",
        type: "object",
        schemaType: "object",
        error: exports$12.error,
        code(cxt) {
          const [propDeps, schDeps] = splitDependencies(cxt);
          validatePropertyDeps(cxt, propDeps);
          validateSchemaDeps(cxt, schDeps);
        }
      };
      function splitDependencies({ schema }) {
        const propertyDeps = {};
        const schemaDeps = {};
        for (const key in schema) {
          if (key === "__proto__")
            continue;
          const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps;
          deps[key] = schema[key];
        }
        return [propertyDeps, schemaDeps];
      }
      function validatePropertyDeps(cxt, propertyDeps = cxt.schema) {
        const { gen, data, it: it2 } = cxt;
        if (Object.keys(propertyDeps).length === 0)
          return;
        const missing = gen.let("missing");
        for (const prop in propertyDeps) {
          const deps = propertyDeps[prop];
          if (deps.length === 0)
            continue;
          const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it2.opts.ownProperties);
          cxt.setParams({
            property: prop,
            depsCount: deps.length,
            deps: deps.join(", ")
          });
          if (it2.allErrors) {
            gen.if(hasProperty, () => {
              for (const depProp of deps) {
                (0, code_1.checkReportMissingProp)(cxt, depProp);
              }
            });
          } else {
            gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`);
            (0, code_1.reportMissingProp)(cxt, missing);
            gen.else();
          }
        }
      }
      exports$12.validatePropertyDeps = validatePropertyDeps;
      function validateSchemaDeps(cxt, schemaDeps = cxt.schema) {
        const { gen, data, keyword: keyword2, it: it2 } = cxt;
        const valid = gen.name("valid");
        for (const prop in schemaDeps) {
          if ((0, util_1.alwaysValidSchema)(it2, schemaDeps[prop]))
            continue;
          gen.if(
            (0, code_1.propertyInData)(gen, data, prop, it2.opts.ownProperties),
            () => {
              const schCxt = cxt.subschema({ keyword: keyword2, schemaProp: prop }, valid);
              cxt.mergeValidEvaluated(schCxt, valid);
            },
            () => gen.var(valid, true)
            // TODO var
          );
          cxt.ok(valid);
        }
      }
      exports$12.validateSchemaDeps = validateSchemaDeps;
      exports$12.default = def;
    })(dependencies);
    return dependencies;
  }
  var propertyNames = {};
  var hasRequiredPropertyNames;
  function requirePropertyNames() {
    if (hasRequiredPropertyNames) return propertyNames;
    hasRequiredPropertyNames = 1;
    Object.defineProperty(propertyNames, "__esModule", { value: true });
    const codegen_1 = requireCodegen();
    const util_1 = requireUtil();
    const error2 = {
      message: "property name must be valid",
      params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}`
    };
    const def = {
      keyword: "propertyNames",
      type: "object",
      schemaType: ["object", "boolean"],
      error: error2,
      code(cxt) {
        const { gen, schema, data, it: it2 } = cxt;
        if ((0, util_1.alwaysValidSchema)(it2, schema))
          return;
        const valid = gen.name("valid");
        gen.forIn("key", data, (key) => {
          cxt.setParams({ propertyName: key });
          cxt.subschema({
            keyword: "propertyNames",
            data: key,
            dataTypes: ["string"],
            propertyName: key,
            compositeRule: true
          }, valid);
          gen.if((0, codegen_1.not)(valid), () => {
            cxt.error(true);
            if (!it2.allErrors)
              gen.break();
          });
        });
        cxt.ok(valid);
      }
    };
    propertyNames.default = def;
    return propertyNames;
  }
  var additionalProperties = {};
  var hasRequiredAdditionalProperties;
  function requireAdditionalProperties() {
    if (hasRequiredAdditionalProperties) return additionalProperties;
    hasRequiredAdditionalProperties = 1;
    Object.defineProperty(additionalProperties, "__esModule", { value: true });
    const code_1 = requireCode();
    const codegen_1 = requireCodegen();
    const names_1 = requireNames();
    const util_1 = requireUtil();
    const error2 = {
      message: "must NOT have additional properties",
      params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}`
    };
    const def = {
      keyword: "additionalProperties",
      type: ["object"],
      schemaType: ["boolean", "object"],
      allowUndefined: true,
      trackErrors: true,
      error: error2,
      code(cxt) {
        const { gen, schema, parentSchema, data, errsCount, it: it2 } = cxt;
        if (!errsCount)
          throw new Error("ajv implementation error");
        const { allErrors, opts } = it2;
        it2.props = true;
        if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it2, schema))
          return;
        const props = (0, code_1.allSchemaProperties)(parentSchema.properties);
        const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties);
        checkAdditionalProperties();
        cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);
        function checkAdditionalProperties() {
          gen.forIn("key", data, (key) => {
            if (!props.length && !patProps.length)
              additionalPropertyCode(key);
            else
              gen.if(isAdditional(key), () => additionalPropertyCode(key));
          });
        }
        function isAdditional(key) {
          let definedProp;
          if (props.length > 8) {
            const propsSchema = (0, util_1.schemaRefOrVal)(it2, parentSchema.properties, "properties");
            definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key);
          } else if (props.length) {
            definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`));
          } else {
            definedProp = codegen_1.nil;
          }
          if (patProps.length) {
            definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`));
          }
          return (0, codegen_1.not)(definedProp);
        }
        function deleteAdditional(key) {
          gen.code((0, codegen_1._)`delete ${data}[${key}]`);
        }
        function additionalPropertyCode(key) {
          if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) {
            deleteAdditional(key);
            return;
          }
          if (schema === false) {
            cxt.setParams({ additionalProperty: key });
            cxt.error();
            if (!allErrors)
              gen.break();
            return;
          }
          if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it2, schema)) {
            const valid = gen.name("valid");
            if (opts.removeAdditional === "failing") {
              applyAdditionalSchema(key, valid, false);
              gen.if((0, codegen_1.not)(valid), () => {
                cxt.reset();
                deleteAdditional(key);
              });
            } else {
              applyAdditionalSchema(key, valid);
              if (!allErrors)
                gen.if((0, codegen_1.not)(valid), () => gen.break());
            }
          }
        }
        function applyAdditionalSchema(key, valid, errors2) {
          const subschema2 = {
            keyword: "additionalProperties",
            dataProp: key,
            dataPropType: util_1.Type.Str
          };
          if (errors2 === false) {
            Object.assign(subschema2, {
              compositeRule: true,
              createErrors: false,
              allErrors: false
            });
          }
          cxt.subschema(subschema2, valid);
        }
      }
    };
    additionalProperties.default = def;
    return additionalProperties;
  }
  var properties$1 = {};
  var hasRequiredProperties;
  function requireProperties() {
    if (hasRequiredProperties) return properties$1;
    hasRequiredProperties = 1;
    Object.defineProperty(properties$1, "__esModule", { value: true });
    const validate_1 = requireValidate();
    const code_1 = requireCode();
    const util_1 = requireUtil();
    const additionalProperties_1 = requireAdditionalProperties();
    const def = {
      keyword: "properties",
      type: "object",
      schemaType: "object",
      code(cxt) {
        const { gen, schema, parentSchema, data, it: it2 } = cxt;
        if (it2.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) {
          additionalProperties_1.default.code(new validate_1.KeywordCxt(it2, additionalProperties_1.default, "additionalProperties"));
        }
        const allProps = (0, code_1.allSchemaProperties)(schema);
        for (const prop of allProps) {
          it2.definedProperties.add(prop);
        }
        if (it2.opts.unevaluated && allProps.length && it2.props !== true) {
          it2.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it2.props);
        }
        const properties2 = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it2, schema[p]));
        if (properties2.length === 0)
          return;
        const valid = gen.name("valid");
        for (const prop of properties2) {
          if (hasDefault(prop)) {
            applyPropertySchema(prop);
          } else {
            gen.if((0, code_1.propertyInData)(gen, data, prop, it2.opts.ownProperties));
            applyPropertySchema(prop);
            if (!it2.allErrors)
              gen.else().var(valid, true);
            gen.endIf();
          }
          cxt.it.definedProperties.add(prop);
          cxt.ok(valid);
        }
        function hasDefault(prop) {
          return it2.opts.useDefaults && !it2.compositeRule && schema[prop].default !== void 0;
        }
        function applyPropertySchema(prop) {
          cxt.subschema({
            keyword: "properties",
            schemaProp: prop,
            dataProp: prop
          }, valid);
        }
      }
    };
    properties$1.default = def;
    return properties$1;
  }
  var patternProperties = {};
  var hasRequiredPatternProperties;
  function requirePatternProperties() {
    if (hasRequiredPatternProperties) return patternProperties;
    hasRequiredPatternProperties = 1;
    Object.defineProperty(patternProperties, "__esModule", { value: true });
    const code_1 = requireCode();
    const codegen_1 = requireCodegen();
    const util_1 = requireUtil();
    const util_2 = requireUtil();
    const def = {
      keyword: "patternProperties",
      type: "object",
      schemaType: "object",
      code(cxt) {
        const { gen, schema, data, parentSchema, it: it2 } = cxt;
        const { opts } = it2;
        const patterns = (0, code_1.allSchemaProperties)(schema);
        const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it2, schema[p]));
        if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it2.opts.unevaluated || it2.props === true)) {
          return;
        }
        const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties;
        const valid = gen.name("valid");
        if (it2.props !== true && !(it2.props instanceof codegen_1.Name)) {
          it2.props = (0, util_2.evaluatedPropsToName)(gen, it2.props);
        }
        const { props } = it2;
        validatePatternProperties();
        function validatePatternProperties() {
          for (const pat of patterns) {
            if (checkProperties)
              checkMatchingProperties(pat);
            if (it2.allErrors) {
              validateProperties(pat);
            } else {
              gen.var(valid, true);
              validateProperties(pat);
              gen.if(valid);
            }
          }
        }
        function checkMatchingProperties(pat) {
          for (const prop in checkProperties) {
            if (new RegExp(pat).test(prop)) {
              (0, util_1.checkStrictMode)(it2, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`);
            }
          }
        }
        function validateProperties(pat) {
          gen.forIn("key", data, (key) => {
            gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => {
              const alwaysValid = alwaysValidPatterns.includes(pat);
              if (!alwaysValid) {
                cxt.subschema({
                  keyword: "patternProperties",
                  schemaProp: pat,
                  dataProp: key,
                  dataPropType: util_2.Type.Str
                }, valid);
              }
              if (it2.opts.unevaluated && props !== true) {
                gen.assign((0, codegen_1._)`${props}[${key}]`, true);
              } else if (!alwaysValid && !it2.allErrors) {
                gen.if((0, codegen_1.not)(valid), () => gen.break());
              }
            });
          });
        }
      }
    };
    patternProperties.default = def;
    return patternProperties;
  }
  var not = {};
  var hasRequiredNot;
  function requireNot() {
    if (hasRequiredNot) return not;
    hasRequiredNot = 1;
    Object.defineProperty(not, "__esModule", { value: true });
    const util_1 = requireUtil();
    const def = {
      keyword: "not",
      schemaType: ["object", "boolean"],
      trackErrors: true,
      code(cxt) {
        const { gen, schema, it: it2 } = cxt;
        if ((0, util_1.alwaysValidSchema)(it2, schema)) {
          cxt.fail();
          return;
        }
        const valid = gen.name("valid");
        cxt.subschema({
          keyword: "not",
          compositeRule: true,
          createErrors: false,
          allErrors: false
        }, valid);
        cxt.failResult(valid, () => cxt.reset(), () => cxt.error());
      },
      error: { message: "must NOT be valid" }
    };
    not.default = def;
    return not;
  }
  var anyOf = {};
  var hasRequiredAnyOf;
  function requireAnyOf() {
    if (hasRequiredAnyOf) return anyOf;
    hasRequiredAnyOf = 1;
    Object.defineProperty(anyOf, "__esModule", { value: true });
    const code_1 = requireCode();
    const def = {
      keyword: "anyOf",
      schemaType: "array",
      trackErrors: true,
      code: code_1.validateUnion,
      error: { message: "must match a schema in anyOf" }
    };
    anyOf.default = def;
    return anyOf;
  }
  var oneOf = {};
  var hasRequiredOneOf;
  function requireOneOf() {
    if (hasRequiredOneOf) return oneOf;
    hasRequiredOneOf = 1;
    Object.defineProperty(oneOf, "__esModule", { value: true });
    const codegen_1 = requireCodegen();
    const util_1 = requireUtil();
    const error2 = {
      message: "must match exactly one schema in oneOf",
      params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}`
    };
    const def = {
      keyword: "oneOf",
      schemaType: "array",
      trackErrors: true,
      error: error2,
      code(cxt) {
        const { gen, schema, parentSchema, it: it2 } = cxt;
        if (!Array.isArray(schema))
          throw new Error("ajv implementation error");
        if (it2.opts.discriminator && parentSchema.discriminator)
          return;
        const schArr = schema;
        const valid = gen.let("valid", false);
        const passing = gen.let("passing", null);
        const schValid = gen.name("_valid");
        cxt.setParams({ passing });
        gen.block(validateOneOf);
        cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
        function validateOneOf() {
          schArr.forEach((sch, i2) => {
            let schCxt;
            if ((0, util_1.alwaysValidSchema)(it2, sch)) {
              gen.var(schValid, true);
            } else {
              schCxt = cxt.subschema({
                keyword: "oneOf",
                schemaProp: i2,
                compositeRule: true
              }, schValid);
            }
            if (i2 > 0) {
              gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i2}]`).else();
            }
            gen.if(schValid, () => {
              gen.assign(valid, true);
              gen.assign(passing, i2);
              if (schCxt)
                cxt.mergeEvaluated(schCxt, codegen_1.Name);
            });
          });
        }
      }
    };
    oneOf.default = def;
    return oneOf;
  }
  var allOf = {};
  var hasRequiredAllOf;
  function requireAllOf() {
    if (hasRequiredAllOf) return allOf;
    hasRequiredAllOf = 1;
    Object.defineProperty(allOf, "__esModule", { value: true });
    const util_1 = requireUtil();
    const def = {
      keyword: "allOf",
      schemaType: "array",
      code(cxt) {
        const { gen, schema, it: it2 } = cxt;
        if (!Array.isArray(schema))
          throw new Error("ajv implementation error");
        const valid = gen.name("valid");
        schema.forEach((sch, i2) => {
          if ((0, util_1.alwaysValidSchema)(it2, sch))
            return;
          const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i2 }, valid);
          cxt.ok(valid);
          cxt.mergeEvaluated(schCxt);
        });
      }
    };
    allOf.default = def;
    return allOf;
  }
  var _if = {};
  var hasRequired_if;
  function require_if() {
    if (hasRequired_if) return _if;
    hasRequired_if = 1;
    Object.defineProperty(_if, "__esModule", { value: true });
    const codegen_1 = requireCodegen();
    const util_1 = requireUtil();
    const error2 = {
      message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`,
      params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}`
    };
    const def = {
      keyword: "if",
      schemaType: ["object", "boolean"],
      trackErrors: true,
      error: error2,
      code(cxt) {
        const { gen, parentSchema, it: it2 } = cxt;
        if (parentSchema.then === void 0 && parentSchema.else === void 0) {
          (0, util_1.checkStrictMode)(it2, '"if" without "then" and "else" is ignored');
        }
        const hasThen = hasSchema(it2, "then");
        const hasElse = hasSchema(it2, "else");
        if (!hasThen && !hasElse)
          return;
        const valid = gen.let("valid", true);
        const schValid = gen.name("_valid");
        validateIf();
        cxt.reset();
        if (hasThen && hasElse) {
          const ifClause = gen.let("ifClause");
          cxt.setParams({ ifClause });
          gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause));
        } else if (hasThen) {
          gen.if(schValid, validateClause("then"));
        } else {
          gen.if((0, codegen_1.not)(schValid), validateClause("else"));
        }
        cxt.pass(valid, () => cxt.error(true));
        function validateIf() {
          const schCxt = cxt.subschema({
            keyword: "if",
            compositeRule: true,
            createErrors: false,
            allErrors: false
          }, schValid);
          cxt.mergeEvaluated(schCxt);
        }
        function validateClause(keyword2, ifClause) {
          return () => {
            const schCxt = cxt.subschema({ keyword: keyword2 }, schValid);
            gen.assign(valid, schValid);
            cxt.mergeValidEvaluated(schCxt, valid);
            if (ifClause)
              gen.assign(ifClause, (0, codegen_1._)`${keyword2}`);
            else
              cxt.setParams({ ifClause: keyword2 });
          };
        }
      }
    };
    function hasSchema(it2, keyword2) {
      const schema = it2.schema[keyword2];
      return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it2, schema);
    }
    _if.default = def;
    return _if;
  }
  var thenElse = {};
  var hasRequiredThenElse;
  function requireThenElse() {
    if (hasRequiredThenElse) return thenElse;
    hasRequiredThenElse = 1;
    Object.defineProperty(thenElse, "__esModule", { value: true });
    const util_1 = requireUtil();
    const def = {
      keyword: ["then", "else"],
      schemaType: ["object", "boolean"],
      code({ keyword: keyword2, parentSchema, it: it2 }) {
        if (parentSchema.if === void 0)
          (0, util_1.checkStrictMode)(it2, `"${keyword2}" without "if" is ignored`);
      }
    };
    thenElse.default = def;
    return thenElse;
  }
  var hasRequiredApplicator;
  function requireApplicator() {
    if (hasRequiredApplicator) return applicator;
    hasRequiredApplicator = 1;
    Object.defineProperty(applicator, "__esModule", { value: true });
    const additionalItems_1 = requireAdditionalItems();
    const prefixItems_1 = requirePrefixItems();
    const items_1 = requireItems();
    const items2020_1 = requireItems2020();
    const contains_1 = requireContains();
    const dependencies_1 = requireDependencies();
    const propertyNames_1 = requirePropertyNames();
    const additionalProperties_1 = requireAdditionalProperties();
    const properties_1 = requireProperties();
    const patternProperties_1 = requirePatternProperties();
    const not_1 = requireNot();
    const anyOf_1 = requireAnyOf();
    const oneOf_1 = requireOneOf();
    const allOf_1 = requireAllOf();
    const if_1 = require_if();
    const thenElse_1 = requireThenElse();
    function getApplicator(draft2020 = false) {
      const applicator2 = [
        // any
        not_1.default,
        anyOf_1.default,
        oneOf_1.default,
        allOf_1.default,
        if_1.default,
        thenElse_1.default,
        // object
        propertyNames_1.default,
        additionalProperties_1.default,
        dependencies_1.default,
        properties_1.default,
        patternProperties_1.default
      ];
      if (draft2020)
        applicator2.push(prefixItems_1.default, items2020_1.default);
      else
        applicator2.push(additionalItems_1.default, items_1.default);
      applicator2.push(contains_1.default);
      return applicator2;
    }
    applicator.default = getApplicator;
    return applicator;
  }
  var format$1 = {};
  var format = {};
  var hasRequiredFormat$1;
  function requireFormat$1() {
    if (hasRequiredFormat$1) return format;
    hasRequiredFormat$1 = 1;
    Object.defineProperty(format, "__esModule", { value: true });
    const codegen_1 = requireCodegen();
    const error2 = {
      message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`,
      params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}`
    };
    const def = {
      keyword: "format",
      type: ["number", "string"],
      schemaType: "string",
      $data: true,
      error: error2,
      code(cxt, ruleType) {
        const { gen, data, $data, schema, schemaCode, it: it2 } = cxt;
        const { opts, errSchemaPath, schemaEnv, self: self2 } = it2;
        if (!opts.validateFormats)
          return;
        if ($data)
          validate$DataFormat();
        else
          validateFormat();
        function validate$DataFormat() {
          const fmts = gen.scopeValue("formats", {
            ref: self2.formats,
            code: opts.code.formats
          });
          const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`);
          const fType = gen.let("fType");
          const format2 = gen.let("format");
          gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format2, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format2, fDef));
          cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt()));
          function unknownFmt() {
            if (opts.strictSchema === false)
              return codegen_1.nil;
            return (0, codegen_1._)`${schemaCode} && !${format2}`;
          }
          function invalidFmt() {
            const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format2}(${data}) : ${format2}(${data}))` : (0, codegen_1._)`${format2}(${data})`;
            const validData = (0, codegen_1._)`(typeof ${format2} == "function" ? ${callFormat} : ${format2}.test(${data}))`;
            return (0, codegen_1._)`${format2} && ${format2} !== true && ${fType} === ${ruleType} && !${validData}`;
          }
        }
        function validateFormat() {
          const formatDef = self2.formats[schema];
          if (!formatDef) {
            unknownFormat();
            return;
          }
          if (formatDef === true)
            return;
          const [fmtType, format2, fmtRef] = getFormat(formatDef);
          if (fmtType === ruleType)
            cxt.pass(validCondition());
          function unknownFormat() {
            if (opts.strictSchema === false) {
              self2.logger.warn(unknownMsg());
              return;
            }
            throw new Error(unknownMsg());
            function unknownMsg() {
              return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`;
            }
          }
          function getFormat(fmtDef) {
            const code2 = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0;
            const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code: code2 });
            if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) {
              return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._)`${fmt}.validate`];
            }
            return ["string", fmtDef, fmt];
          }
          function validCondition() {
            if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) {
              if (!schemaEnv.$async)
                throw new Error("async format in sync schema");
              return (0, codegen_1._)`await ${fmtRef}(${data})`;
            }
            return typeof format2 == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`;
          }
        }
      }
    };
    format.default = def;
    return format;
  }
  var hasRequiredFormat;
  function requireFormat() {
    if (hasRequiredFormat) return format$1;
    hasRequiredFormat = 1;
    Object.defineProperty(format$1, "__esModule", { value: true });
    const format_1 = requireFormat$1();
    const format2 = [format_1.default];
    format$1.default = format2;
    return format$1;
  }
  var metadata = {};
  var hasRequiredMetadata;
  function requireMetadata() {
    if (hasRequiredMetadata) return metadata;
    hasRequiredMetadata = 1;
    Object.defineProperty(metadata, "__esModule", { value: true });
    metadata.contentVocabulary = metadata.metadataVocabulary = void 0;
    metadata.metadataVocabulary = [
      "title",
      "description",
      "default",
      "deprecated",
      "readOnly",
      "writeOnly",
      "examples"
    ];
    metadata.contentVocabulary = [
      "contentMediaType",
      "contentEncoding",
      "contentSchema"
    ];
    return metadata;
  }
  var hasRequiredDraft7;
  function requireDraft7() {
    if (hasRequiredDraft7) return draft7;
    hasRequiredDraft7 = 1;
    Object.defineProperty(draft7, "__esModule", { value: true });
    const core_1 = requireCore();
    const validation_1 = requireValidation();
    const applicator_1 = requireApplicator();
    const format_1 = requireFormat();
    const metadata_1 = requireMetadata();
    const draft7Vocabularies = [
      core_1.default,
      validation_1.default,
      (0, applicator_1.default)(),
      format_1.default,
      metadata_1.metadataVocabulary,
      metadata_1.contentVocabulary
    ];
    draft7.default = draft7Vocabularies;
    return draft7;
  }
  var discriminator = {};
  var types$1 = {};
  var hasRequiredTypes;
  function requireTypes() {
    if (hasRequiredTypes) return types$1;
    hasRequiredTypes = 1;
    Object.defineProperty(types$1, "__esModule", { value: true });
    types$1.DiscrError = void 0;
    var DiscrError;
    (function(DiscrError2) {
      DiscrError2["Tag"] = "tag";
      DiscrError2["Mapping"] = "mapping";
    })(DiscrError || (types$1.DiscrError = DiscrError = {}));
    return types$1;
  }
  var hasRequiredDiscriminator;
  function requireDiscriminator() {
    if (hasRequiredDiscriminator) return discriminator;
    hasRequiredDiscriminator = 1;
    Object.defineProperty(discriminator, "__esModule", { value: true });
    const codegen_1 = requireCodegen();
    const types_1 = requireTypes();
    const compile_1 = requireCompile();
    const ref_error_1 = requireRef_error();
    const util_1 = requireUtil();
    const error2 = {
      message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`,
      params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`
    };
    const def = {
      keyword: "discriminator",
      type: "object",
      schemaType: "object",
      error: error2,
      code(cxt) {
        const { gen, data, schema, parentSchema, it: it2 } = cxt;
        const { oneOf: oneOf2 } = parentSchema;
        if (!it2.opts.discriminator) {
          throw new Error("discriminator: requires discriminator option");
        }
        const tagName = schema.propertyName;
        if (typeof tagName != "string")
          throw new Error("discriminator: requires propertyName");
        if (schema.mapping)
          throw new Error("discriminator: mapping is not supported");
        if (!oneOf2)
          throw new Error("discriminator: requires oneOf keyword");
        const valid = gen.let("valid", false);
        const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`);
        gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName }));
        cxt.ok(valid);
        function validateMapping() {
          const mapping = getMapping();
          gen.if(false);
          for (const tagValue in mapping) {
            gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`);
            gen.assign(valid, applyTagSchema(mapping[tagValue]));
          }
          gen.else();
          cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName });
          gen.endIf();
        }
        function applyTagSchema(schemaProp) {
          const _valid = gen.name("valid");
          const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid);
          cxt.mergeEvaluated(schCxt, codegen_1.Name);
          return _valid;
        }
        function getMapping() {
          var _a3;
          const oneOfMapping = {};
          const topRequired = hasRequired(parentSchema);
          let tagRequired = true;
          for (let i2 = 0; i2 < oneOf2.length; i2++) {
            let sch = oneOf2[i2];
            if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it2.self.RULES)) {
              const ref2 = sch.$ref;
              sch = compile_1.resolveRef.call(it2.self, it2.schemaEnv.root, it2.baseId, ref2);
              if (sch instanceof compile_1.SchemaEnv)
                sch = sch.schema;
              if (sch === void 0)
                throw new ref_error_1.default(it2.opts.uriResolver, it2.baseId, ref2);
            }
            const propSch = (_a3 = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a3 === void 0 ? void 0 : _a3[tagName];
            if (typeof propSch != "object") {
              throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`);
            }
            tagRequired = tagRequired && (topRequired || hasRequired(sch));
            addMappings(propSch, i2);
          }
          if (!tagRequired)
            throw new Error(`discriminator: "${tagName}" must be required`);
          return oneOfMapping;
          function hasRequired({ required: required2 }) {
            return Array.isArray(required2) && required2.includes(tagName);
          }
          function addMappings(sch, i2) {
            if (sch.const) {
              addMapping(sch.const, i2);
            } else if (sch.enum) {
              for (const tagValue of sch.enum) {
                addMapping(tagValue, i2);
              }
            } else {
              throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`);
            }
          }
          function addMapping(tagValue, i2) {
            if (typeof tagValue != "string" || tagValue in oneOfMapping) {
              throw new Error(`discriminator: "${tagName}" values must be unique strings`);
            }
            oneOfMapping[tagValue] = i2;
          }
        }
      }
    };
    discriminator.default = def;
    return discriminator;
  }
  const $schema = "http://json-schema.org/draft-07/schema#";
  const $id = "http://json-schema.org/draft-07/schema#";
  const title = "Core schema meta-schema";
  const definitions = { "schemaArray": { "type": "array", "minItems": 1, "items": { "$ref": "#" } }, "nonNegativeInteger": { "type": "integer", "minimum": 0 }, "nonNegativeIntegerDefault0": { "allOf": [{ "$ref": "#/definitions/nonNegativeInteger" }, { "default": 0 }] }, "simpleTypes": { "enum": ["array", "boolean", "integer", "null", "number", "object", "string"] }, "stringArray": { "type": "array", "items": { "type": "string" }, "uniqueItems": true, "default": [] } };
  const type = ["object", "boolean"];
  const properties = { "$id": { "type": "string", "format": "uri-reference" }, "$schema": { "type": "string", "format": "uri" }, "$ref": { "type": "string", "format": "uri-reference" }, "$comment": { "type": "string" }, "title": { "type": "string" }, "description": { "type": "string" }, "default": true, "readOnly": { "type": "boolean", "default": false }, "examples": { "type": "array", "items": true }, "multipleOf": { "type": "number", "exclusiveMinimum": 0 }, "maximum": { "type": "number" }, "exclusiveMaximum": { "type": "number" }, "minimum": { "type": "number" }, "exclusiveMinimum": { "type": "number" }, "maxLength": { "$ref": "#/definitions/nonNegativeInteger" }, "minLength": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, "pattern": { "type": "string", "format": "regex" }, "additionalItems": { "$ref": "#" }, "items": { "anyOf": [{ "$ref": "#" }, { "$ref": "#/definitions/schemaArray" }], "default": true }, "maxItems": { "$ref": "#/definitions/nonNegativeInteger" }, "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, "uniqueItems": { "type": "boolean", "default": false }, "contains": { "$ref": "#" }, "maxProperties": { "$ref": "#/definitions/nonNegativeInteger" }, "minProperties": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, "required": { "$ref": "#/definitions/stringArray" }, "additionalProperties": { "$ref": "#" }, "definitions": { "type": "object", "additionalProperties": { "$ref": "#" }, "default": {} }, "properties": { "type": "object", "additionalProperties": { "$ref": "#" }, "default": {} }, "patternProperties": { "type": "object", "additionalProperties": { "$ref": "#" }, "propertyNames": { "format": "regex" }, "default": {} }, "dependencies": { "type": "object", "additionalProperties": { "anyOf": [{ "$ref": "#" }, { "$ref": "#/definitions/stringArray" }] } }, "propertyNames": { "$ref": "#" }, "const": true, "enum": { "type": "array", "items": true, "minItems": 1, "uniqueItems": true }, "type": { "anyOf": [{ "$ref": "#/definitions/simpleTypes" }, { "type": "array", "items": { "$ref": "#/definitions/simpleTypes" }, "minItems": 1, "uniqueItems": true }] }, "format": { "type": "string" }, "contentMediaType": { "type": "string" }, "contentEncoding": { "type": "string" }, "if": { "$ref": "#" }, "then": { "$ref": "#" }, "else": { "$ref": "#" }, "allOf": { "$ref": "#/definitions/schemaArray" }, "anyOf": { "$ref": "#/definitions/schemaArray" }, "oneOf": { "$ref": "#/definitions/schemaArray" }, "not": { "$ref": "#" } };
  const require$$3 = {
    $schema,
    $id,
    title,
    definitions,
    type,
    properties,
    "default": true
  };
  var hasRequiredAjv;
  function requireAjv() {
    if (hasRequiredAjv) return ajv.exports;
    hasRequiredAjv = 1;
    (function(module2, exports$12) {
      Object.defineProperty(exports$12, "__esModule", { value: true });
      exports$12.MissingRefError = exports$12.ValidationError = exports$12.CodeGen = exports$12.Name = exports$12.nil = exports$12.stringify = exports$12.str = exports$12._ = exports$12.KeywordCxt = exports$12.Ajv = void 0;
      const core_1 = requireCore$1();
      const draft7_1 = requireDraft7();
      const discriminator_1 = requireDiscriminator();
      const draft7MetaSchema = require$$3;
      const META_SUPPORT_DATA = ["/properties"];
      const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema";
      class Ajv2 extends core_1.default {
        _addVocabularies() {
          super._addVocabularies();
          draft7_1.default.forEach((v) => this.addVocabulary(v));
          if (this.opts.discriminator)
            this.addKeyword(discriminator_1.default);
        }
        _addDefaultMetaSchema() {
          super._addDefaultMetaSchema();
          if (!this.opts.meta)
            return;
          const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema;
          this.addMetaSchema(metaSchema, META_SCHEMA_ID, false);
          this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID;
        }
        defaultMeta() {
          return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0);
        }
      }
      exports$12.Ajv = Ajv2;
      module2.exports = exports$12 = Ajv2;
      module2.exports.Ajv = Ajv2;
      Object.defineProperty(exports$12, "__esModule", { value: true });
      exports$12.default = Ajv2;
      var validate_1 = requireValidate();
      Object.defineProperty(exports$12, "KeywordCxt", { enumerable: true, get: function() {
        return validate_1.KeywordCxt;
      } });
      var codegen_1 = requireCodegen();
      Object.defineProperty(exports$12, "_", { enumerable: true, get: function() {
        return codegen_1._;
      } });
      Object.defineProperty(exports$12, "str", { enumerable: true, get: function() {
        return codegen_1.str;
      } });
      Object.defineProperty(exports$12, "stringify", { enumerable: true, get: function() {
        return codegen_1.stringify;
      } });
      Object.defineProperty(exports$12, "nil", { enumerable: true, get: function() {
        return codegen_1.nil;
      } });
      Object.defineProperty(exports$12, "Name", { enumerable: true, get: function() {
        return codegen_1.Name;
      } });
      Object.defineProperty(exports$12, "CodeGen", { enumerable: true, get: function() {
        return codegen_1.CodeGen;
      } });
      var validation_error_1 = requireValidation_error();
      Object.defineProperty(exports$12, "ValidationError", { enumerable: true, get: function() {
        return validation_error_1.default;
      } });
      var ref_error_1 = requireRef_error();
      Object.defineProperty(exports$12, "MissingRefError", { enumerable: true, get: function() {
        return ref_error_1.default;
      } });
    })(ajv, ajv.exports);
    return ajv.exports;
  }
  var ajvExports = requireAjv();
  const Ajv = /* @__PURE__ */ getDefaultExportFromCjs$1(ajvExports);
  var dist = { exports: {} };
  var formats = {};
  var hasRequiredFormats;
  function requireFormats() {
    if (hasRequiredFormats) return formats;
    hasRequiredFormats = 1;
    (function(exports$12) {
      Object.defineProperty(exports$12, "__esModule", { value: true });
      exports$12.formatNames = exports$12.fastFormats = exports$12.fullFormats = void 0;
      function fmtDef(validate2, compare) {
        return { validate: validate2, compare };
      }
      exports$12.fullFormats = {
        // date: http://tools.ietf.org/html/rfc3339#section-5.6
        date: fmtDef(date2, compareDate),
        // date-time: http://tools.ietf.org/html/rfc3339#section-5.6
        time: fmtDef(getTime(true), compareTime),
        "date-time": fmtDef(getDateTime(true), compareDateTime),
        "iso-time": fmtDef(getTime(), compareIsoTime),
        "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime),
        // duration: https://tools.ietf.org/html/rfc3339#appendix-A
        duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,
        uri: uri2,
        "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,
        // uri-template: https://tools.ietf.org/html/rfc6570
        "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,
        // For the source: https://gist.github.com/dperini/729294
        // For test cases: https://mathiasbynens.be/demo/url-regex
        url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,
        email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,
        hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,
        // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html
        ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,
        ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,
        regex,
        // uuid: http://tools.ietf.org/html/rfc4122
        uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,
        // JSON-pointer: https://tools.ietf.org/html/rfc6901
        // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A
        "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/,
        "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,
        // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00
        "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,
        // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types
        // byte: https://github.com/miguelmota/is-base64
        byte,
        // signed 32 bit integer
        int32: { type: "number", validate: validateInt32 },
        // signed 64 bit integer
        int64: { type: "number", validate: validateInt64 },
        // C-type float
        float: { type: "number", validate: validateNumber },
        // C-type double
        double: { type: "number", validate: validateNumber },
        // hint to the UI to hide input strings
        password: true,
        // unchecked string payload
        binary: true
      };
      exports$12.fastFormats = __spreadProps(__spreadValues({}, exports$12.fullFormats), {
        date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate),
        time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime),
        "date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime),
        "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime),
        "iso-date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoDateTime),
        // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js
        uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,
        "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,
        // email (sources from jsen validator):
        // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363
        // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation')
        email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i
      });
      exports$12.formatNames = Object.keys(exports$12.fullFormats);
      function isLeapYear(year) {
        return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
      }
      const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
      const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
      function date2(str) {
        const matches = DATE.exec(str);
        if (!matches)
          return false;
        const year = +matches[1];
        const month = +matches[2];
        const day = +matches[3];
        return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]);
      }
      function compareDate(d1, d2) {
        if (!(d1 && d2))
          return void 0;
        if (d1 > d2)
          return 1;
        if (d1 < d2)
          return -1;
        return 0;
      }
      const TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;
      function getTime(strictTimeZone) {
        return function time2(str) {
          const matches = TIME.exec(str);
          if (!matches)
            return false;
          const hr = +matches[1];
          const min = +matches[2];
          const sec = +matches[3];
          const tz = matches[4];
          const tzSign = matches[5] === "-" ? -1 : 1;
          const tzH = +(matches[6] || 0);
          const tzM = +(matches[7] || 0);
          if (tzH > 23 || tzM > 59 || strictTimeZone && !tz)
            return false;
          if (hr <= 23 && min <= 59 && sec < 60)
            return true;
          const utcMin = min - tzM * tzSign;
          const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0);
          return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61;
        };
      }
      function compareTime(s1, s2) {
        if (!(s1 && s2))
          return void 0;
        const t1 = (/* @__PURE__ */ new Date("2020-01-01T" + s1)).valueOf();
        const t2 = (/* @__PURE__ */ new Date("2020-01-01T" + s2)).valueOf();
        if (!(t1 && t2))
          return void 0;
        return t1 - t2;
      }
      function compareIsoTime(t1, t2) {
        if (!(t1 && t2))
          return void 0;
        const a1 = TIME.exec(t1);
        const a2 = TIME.exec(t2);
        if (!(a1 && a2))
          return void 0;
        t1 = a1[1] + a1[2] + a1[3];
        t2 = a2[1] + a2[2] + a2[3];
        if (t1 > t2)
          return 1;
        if (t1 < t2)
          return -1;
        return 0;
      }
      const DATE_TIME_SEPARATOR = /t|\s/i;
      function getDateTime(strictTimeZone) {
        const time2 = getTime(strictTimeZone);
        return function date_time(str) {
          const dateTime = str.split(DATE_TIME_SEPARATOR);
          return dateTime.length === 2 && date2(dateTime[0]) && time2(dateTime[1]);
        };
      }
      function compareDateTime(dt1, dt2) {
        if (!(dt1 && dt2))
          return void 0;
        const d1 = new Date(dt1).valueOf();
        const d2 = new Date(dt2).valueOf();
        if (!(d1 && d2))
          return void 0;
        return d1 - d2;
      }
      function compareIsoDateTime(dt1, dt2) {
        if (!(dt1 && dt2))
          return void 0;
        const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR);
        const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR);
        const res = compareDate(d1, d2);
        if (res === void 0)
          return void 0;
        return res || compareTime(t1, t2);
      }
      const NOT_URI_FRAGMENT = /\/|:/;
      const URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
      function uri2(str) {
        return NOT_URI_FRAGMENT.test(str) && URI.test(str);
      }
      const BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;
      function byte(str) {
        BYTE.lastIndex = 0;
        return BYTE.test(str);
      }
      const MIN_INT32 = -2147483648;
      const MAX_INT32 = __pow(2, 31) - 1;
      function validateInt32(value) {
        return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32;
      }
      function validateInt64(value) {
        return Number.isInteger(value);
      }
      function validateNumber() {
        return true;
      }
      const Z_ANCHOR = /[^\\]\\Z/;
      function regex(str) {
        if (Z_ANCHOR.test(str))
          return false;
        try {
          new RegExp(str);
          return true;
        } catch (e) {
          return false;
        }
      }
    })(formats);
    return formats;
  }
  var limit = {};
  var hasRequiredLimit;
  function requireLimit() {
    if (hasRequiredLimit) return limit;
    hasRequiredLimit = 1;
    (function(exports$12) {
      Object.defineProperty(exports$12, "__esModule", { value: true });
      exports$12.formatLimitDefinition = void 0;
      const ajv_1 = requireAjv();
      const codegen_1 = requireCodegen();
      const ops = codegen_1.operators;
      const KWDs = {
        formatMaximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT },
        formatMinimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT },
        formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE },
        formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE }
      };
      const error2 = {
        message: ({ keyword: keyword2, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword2].okStr} ${schemaCode}`,
        params: ({ keyword: keyword2, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword2].okStr}, limit: ${schemaCode}}`
      };
      exports$12.formatLimitDefinition = {
        keyword: Object.keys(KWDs),
        type: "string",
        schemaType: "string",
        $data: true,
        error: error2,
        code(cxt) {
          const { gen, data, schemaCode, keyword: keyword2, it: it2 } = cxt;
          const { opts, self: self2 } = it2;
          if (!opts.validateFormats)
            return;
          const fCxt = new ajv_1.KeywordCxt(it2, self2.RULES.all.format.definition, "format");
          if (fCxt.$data)
            validate$DataFormat();
          else
            validateFormat();
          function validate$DataFormat() {
            const fmts = gen.scopeValue("formats", {
              ref: self2.formats,
              code: opts.code.formats
            });
            const fmt = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`);
            cxt.fail$data((0, codegen_1.or)((0, codegen_1._)`typeof ${fmt} != "object"`, (0, codegen_1._)`${fmt} instanceof RegExp`, (0, codegen_1._)`typeof ${fmt}.compare != "function"`, compareCode(fmt)));
          }
          function validateFormat() {
            const format2 = fCxt.schema;
            const fmtDef = self2.formats[format2];
            if (!fmtDef || fmtDef === true)
              return;
            if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") {
              throw new Error(`"${keyword2}": format "${format2}" does not define "compare" function`);
            }
            const fmt = gen.scopeValue("formats", {
              key: format2,
              ref: fmtDef,
              code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format2)}` : void 0
            });
            cxt.fail$data(compareCode(fmt));
          }
          function compareCode(fmt) {
            return (0, codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword2].fail} 0`;
          }
        },
        dependencies: ["format"]
      };
      const formatLimitPlugin = (ajv2) => {
        ajv2.addKeyword(exports$12.formatLimitDefinition);
        return ajv2;
      };
      exports$12.default = formatLimitPlugin;
    })(limit);
    return limit;
  }
  var hasRequiredDist;
  function requireDist() {
    if (hasRequiredDist) return dist.exports;
    hasRequiredDist = 1;
    (function(module2, exports$12) {
      Object.defineProperty(exports$12, "__esModule", { value: true });
      const formats_1 = requireFormats();
      const limit_1 = requireLimit();
      const codegen_1 = requireCodegen();
      const fullName = new codegen_1.Name("fullFormats");
      const fastName = new codegen_1.Name("fastFormats");
      const formatsPlugin = (ajv2, opts = { keywords: true }) => {
        if (Array.isArray(opts)) {
          addFormats(ajv2, opts, formats_1.fullFormats, fullName);
          return ajv2;
        }
        const [formats2, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName];
        const list = opts.formats || formats_1.formatNames;
        addFormats(ajv2, list, formats2, exportName);
        if (opts.keywords)
          (0, limit_1.default)(ajv2);
        return ajv2;
      };
      formatsPlugin.get = (name2, mode = "full") => {
        const formats2 = mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats;
        const f = formats2[name2];
        if (!f)
          throw new Error(`Unknown format "${name2}"`);
        return f;
      };
      function addFormats(ajv2, list, fs, exportName) {
        var _a3;
        var _b2;
        (_a3 = (_b2 = ajv2.opts.code).formats) !== null && _a3 !== void 0 ? _a3 : _b2.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`;
        for (const f of list)
          ajv2.addFormat(f, fs[f]);
      }
      module2.exports = exports$12 = formatsPlugin;
      Object.defineProperty(exports$12, "__esModule", { value: true });
      exports$12.default = formatsPlugin;
    })(dist, dist.exports);
    return dist.exports;
  }
  var distExports = requireDist();
  const _addFormats = /* @__PURE__ */ getDefaultExportFromCjs$1(distExports);
  function createDefaultAjvInstance() {
    const ajv2 = new Ajv({
      strict: false,
      validateFormats: true,
      validateSchema: false,
      allErrors: true
    });
    const addFormats = _addFormats;
    addFormats(ajv2);
    return ajv2;
  }
  class AjvJsonSchemaValidator {
    /**
     * Create an AJV validator
     *
     * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created.
     *
     * @example
     * ```typescript
     * // Use default configuration (recommended for most cases)
     * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv';
     * const validator = new AjvJsonSchemaValidator();
     *
     * // Or provide custom AJV instance for advanced configuration
     * import { Ajv } from 'ajv';
     * import addFormats from 'ajv-formats';
     *
     * const ajv = new Ajv({ validateFormats: true });
     * addFormats(ajv);
     * const validator = new AjvJsonSchemaValidator(ajv);
     * ```
     */
    constructor(ajv2) {
      this._ajv = ajv2 != null ? ajv2 : createDefaultAjvInstance();
    }
    /**
     * Create a validator for the given JSON Schema
     *
     * The validator is compiled once and can be reused multiple times.
     * If the schema has an $id, it will be cached by AJV automatically.
     *
     * @param schema - Standard JSON Schema object
     * @returns A validator function that validates input data
     */
    getValidator(schema) {
      var _a3;
      const ajvValidator = "$id" in schema && typeof schema.$id === "string" ? (_a3 = this._ajv.getSchema(schema.$id)) != null ? _a3 : this._ajv.compile(schema) : this._ajv.compile(schema);
      return (input) => {
        const valid = ajvValidator(input);
        if (valid) {
          return {
            valid: true,
            data: input,
            errorMessage: void 0
          };
        } else {
          return {
            valid: false,
            data: void 0,
            errorMessage: this._ajv.errorsText(ajvValidator.errors)
          };
        }
      };
    }
  }
  class ExperimentalServerTasks {
    constructor(_server) {
      this._server = _server;
    }
    /**
     * Sends a request and returns an AsyncGenerator that yields response messages.
     * The generator is guaranteed to end with either a 'result' or 'error' message.
     *
     * This method provides streaming access to request processing, allowing you to
     * observe intermediate task status updates for task-augmented requests.
     *
     * @param request - The request to send
     * @param resultSchema - Zod schema for validating the result
     * @param options - Optional request options (timeout, signal, task creation params, etc.)
     * @returns AsyncGenerator that yields ResponseMessage objects
     *
     * @experimental
     */
    requestStream(request, resultSchema, options) {
      return this._server.requestStream(request, resultSchema, options);
    }
    /**
     * Gets the current status of a task.
     *
     * @param taskId - The task identifier
     * @param options - Optional request options
     * @returns The task status
     *
     * @experimental
     */
    getTask(taskId, options) {
      return __async(this, null, function* () {
        return this._server.getTask({ taskId }, options);
      });
    }
    /**
     * Retrieves the result of a completed task.
     *
     * @param taskId - The task identifier
     * @param resultSchema - Zod schema for validating the result
     * @param options - Optional request options
     * @returns The task result
     *
     * @experimental
     */
    getTaskResult(taskId, resultSchema, options) {
      return __async(this, null, function* () {
        return this._server.getTaskResult({ taskId }, resultSchema, options);
      });
    }
    /**
     * Lists tasks with optional pagination.
     *
     * @param cursor - Optional pagination cursor
     * @param options - Optional request options
     * @returns List of tasks with optional next cursor
     *
     * @experimental
     */
    listTasks(cursor, options) {
      return __async(this, null, function* () {
        return this._server.listTasks(cursor ? { cursor } : void 0, options);
      });
    }
    /**
     * Cancels a running task.
     *
     * @param taskId - The task identifier
     * @param options - Optional request options
     *
     * @experimental
     */
    cancelTask(taskId, options) {
      return __async(this, null, function* () {
        return this._server.cancelTask({ taskId }, options);
      });
    }
  }
  function assertToolsCallTaskCapability(requests, method, entityName) {
    var _a3;
    if (!requests) {
      throw new Error(`${entityName} does not support task creation (required for ${method})`);
    }
    switch (method) {
      case "tools/call":
        if (!((_a3 = requests.tools) == null ? void 0 : _a3.call)) {
          throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`);
        }
        break;
    }
  }
  function assertClientRequestTaskCapability(requests, method, entityName) {
    var _a3, _b2;
    if (!requests) {
      throw new Error(`${entityName} does not support task creation (required for ${method})`);
    }
    switch (method) {
      case "sampling/createMessage":
        if (!((_a3 = requests.sampling) == null ? void 0 : _a3.createMessage)) {
          throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`);
        }
        break;
      case "elicitation/create":
        if (!((_b2 = requests.elicitation) == null ? void 0 : _b2.create)) {
          throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`);
        }
        break;
    }
  }
  class Server extends Protocol {
    /**
     * Initializes this server with the given name and version information.
     */
    constructor(_serverInfo, options) {
      var _a3, _b2;
      super(options);
      this._serverInfo = _serverInfo;
      this._loggingLevels = /* @__PURE__ */ new Map();
      this.LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index2) => [level, index2]));
      this.isMessageIgnored = (level, sessionId) => {
        const currentLevel = this._loggingLevels.get(sessionId);
        return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false;
      };
      this._capabilities = (_a3 = options == null ? void 0 : options.capabilities) != null ? _a3 : {};
      this._instructions = options == null ? void 0 : options.instructions;
      this._jsonSchemaValidator = (_b2 = options == null ? void 0 : options.jsonSchemaValidator) != null ? _b2 : new AjvJsonSchemaValidator();
      this.setRequestHandler(InitializeRequestSchema, (request) => this._oninitialize(request));
      this.setNotificationHandler(InitializedNotificationSchema, () => {
        var _a4;
        return (_a4 = this.oninitialized) == null ? void 0 : _a4.call(this);
      });
      if (this._capabilities.logging) {
        this.setRequestHandler(SetLevelRequestSchema, (request, extra) => __async(this, null, function* () {
          var _a4;
          const transportSessionId = extra.sessionId || ((_a4 = extra.requestInfo) == null ? void 0 : _a4.headers["mcp-session-id"]) || void 0;
          const { level } = request.params;
          const parseResult = LoggingLevelSchema.safeParse(level);
          if (parseResult.success) {
            this._loggingLevels.set(transportSessionId, parseResult.data);
          }
          return {};
        }));
      }
    }
    /**
     * Access experimental features.
     *
     * WARNING: These APIs are experimental and may change without notice.
     *
     * @experimental
     */
    get experimental() {
      if (!this._experimental) {
        this._experimental = {
          tasks: new ExperimentalServerTasks(this)
        };
      }
      return this._experimental;
    }
    /**
     * Registers new capabilities. This can only be called before connecting to a transport.
     *
     * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization).
     */
    registerCapabilities(capabilities) {
      if (this.transport) {
        throw new Error("Cannot register capabilities after connecting to transport");
      }
      this._capabilities = mergeCapabilities(this._capabilities, capabilities);
    }
    /**
     * Override request handler registration to enforce server-side validation for tools/call.
     */
    setRequestHandler(requestSchema, handler) {
      var _a3, _b2, _c2;
      const shape = getObjectShape(requestSchema);
      const methodSchema = shape == null ? void 0 : shape.method;
      if (!methodSchema) {
        throw new Error("Schema is missing a method literal");
      }
      let methodValue;
      if (isZ4Schema(methodSchema)) {
        const v4Schema = methodSchema;
        const v4Def = (_a3 = v4Schema._zod) == null ? void 0 : _a3.def;
        methodValue = (_b2 = v4Def == null ? void 0 : v4Def.value) != null ? _b2 : v4Schema.value;
      } else {
        const v3Schema = methodSchema;
        const legacyDef = v3Schema._def;
        methodValue = (_c2 = legacyDef == null ? void 0 : legacyDef.value) != null ? _c2 : v3Schema.value;
      }
      if (typeof methodValue !== "string") {
        throw new Error("Schema method literal must be a string");
      }
      const method = methodValue;
      if (method === "tools/call") {
        const wrappedHandler = (request, extra) => __async(null, null, function* () {
          const validatedRequest = safeParse$1(CallToolRequestSchema, request);
          if (!validatedRequest.success) {
            const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
            throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call request: ${errorMessage}`);
          }
          const { params } = validatedRequest.data;
          const result2 = yield Promise.resolve(handler(request, extra));
          if (params.task) {
            const taskValidationResult = safeParse$1(CreateTaskResultSchema, result2);
            if (!taskValidationResult.success) {
              const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
              throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);
            }
            return taskValidationResult.data;
          }
          const validationResult = safeParse$1(CallToolResultSchema, result2);
          if (!validationResult.success) {
            const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
            throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call result: ${errorMessage}`);
          }
          return validationResult.data;
        });
        return super.setRequestHandler(requestSchema, wrappedHandler);
      }
      return super.setRequestHandler(requestSchema, handler);
    }
    assertCapabilityForMethod(method) {
      var _a3, _b2, _c2;
      switch (method) {
        case "sampling/createMessage":
          if (!((_a3 = this._clientCapabilities) == null ? void 0 : _a3.sampling)) {
            throw new Error(`Client does not support sampling (required for ${method})`);
          }
          break;
        case "elicitation/create":
          if (!((_b2 = this._clientCapabilities) == null ? void 0 : _b2.elicitation)) {
            throw new Error(`Client does not support elicitation (required for ${method})`);
          }
          break;
        case "roots/list":
          if (!((_c2 = this._clientCapabilities) == null ? void 0 : _c2.roots)) {
            throw new Error(`Client does not support listing roots (required for ${method})`);
          }
          break;
      }
    }
    assertNotificationCapability(method) {
      var _a3, _b2;
      switch (method) {
        case "notifications/message":
          if (!this._capabilities.logging) {
            throw new Error(`Server does not support logging (required for ${method})`);
          }
          break;
        case "notifications/resources/updated":
        case "notifications/resources/list_changed":
          if (!this._capabilities.resources) {
            throw new Error(`Server does not support notifying about resources (required for ${method})`);
          }
          break;
        case "notifications/tools/list_changed":
          if (!this._capabilities.tools) {
            throw new Error(`Server does not support notifying of tool list changes (required for ${method})`);
          }
          break;
        case "notifications/prompts/list_changed":
          if (!this._capabilities.prompts) {
            throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`);
          }
          break;
        case "notifications/elicitation/complete":
          if (!((_b2 = (_a3 = this._clientCapabilities) == null ? void 0 : _a3.elicitation) == null ? void 0 : _b2.url)) {
            throw new Error(`Client does not support URL elicitation (required for ${method})`);
          }
          break;
      }
    }
    assertRequestHandlerCapability(method) {
      if (!this._capabilities) {
        return;
      }
      switch (method) {
        case "completion/complete":
          if (!this._capabilities.completions) {
            throw new Error(`Server does not support completions (required for ${method})`);
          }
          break;
        case "logging/setLevel":
          if (!this._capabilities.logging) {
            throw new Error(`Server does not support logging (required for ${method})`);
          }
          break;
        case "prompts/get":
        case "prompts/list":
          if (!this._capabilities.prompts) {
            throw new Error(`Server does not support prompts (required for ${method})`);
          }
          break;
        case "resources/list":
        case "resources/templates/list":
        case "resources/read":
          if (!this._capabilities.resources) {
            throw new Error(`Server does not support resources (required for ${method})`);
          }
          break;
        case "tools/call":
        case "tools/list":
          if (!this._capabilities.tools) {
            throw new Error(`Server does not support tools (required for ${method})`);
          }
          break;
        case "tasks/get":
        case "tasks/list":
        case "tasks/result":
        case "tasks/cancel":
          if (!this._capabilities.tasks) {
            throw new Error(`Server does not support tasks capability (required for ${method})`);
          }
          break;
      }
    }
    assertTaskCapability(method) {
      var _a3, _b2;
      assertClientRequestTaskCapability((_b2 = (_a3 = this._clientCapabilities) == null ? void 0 : _a3.tasks) == null ? void 0 : _b2.requests, method, "Client");
    }
    assertTaskHandlerCapability(method) {
      var _a3;
      if (!this._capabilities) {
        return;
      }
      assertToolsCallTaskCapability((_a3 = this._capabilities.tasks) == null ? void 0 : _a3.requests, method, "Server");
    }
    _oninitialize(request) {
      return __async(this, null, function* () {
        const requestedVersion = request.params.protocolVersion;
        this._clientCapabilities = request.params.capabilities;
        this._clientVersion = request.params.clientInfo;
        const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : LATEST_PROTOCOL_VERSION;
        return __spreadValues({
          protocolVersion,
          capabilities: this.getCapabilities(),
          serverInfo: this._serverInfo
        }, this._instructions && { instructions: this._instructions });
      });
    }
    /**
     * After initialization has completed, this will be populated with the client's reported capabilities.
     */
    getClientCapabilities() {
      return this._clientCapabilities;
    }
    /**
     * After initialization has completed, this will be populated with information about the client's name and version.
     */
    getClientVersion() {
      return this._clientVersion;
    }
    getCapabilities() {
      return this._capabilities;
    }
    ping() {
      return __async(this, null, function* () {
        return this.request({ method: "ping" }, EmptyResultSchema);
      });
    }
    // Implementation
    createMessage(params, options) {
      return __async(this, null, function* () {
        var _a3, _b2;
        if (params.tools || params.toolChoice) {
          if (!((_b2 = (_a3 = this._clientCapabilities) == null ? void 0 : _a3.sampling) == null ? void 0 : _b2.tools)) {
            throw new Error("Client does not support sampling tools capability.");
          }
        }
        if (params.messages.length > 0) {
          const lastMessage = params.messages[params.messages.length - 1];
          const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content];
          const hasToolResults = lastContent.some((c) => c.type === "tool_result");
          const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : void 0;
          const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : [];
          const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use");
          if (hasToolResults) {
            if (lastContent.some((c) => c.type !== "tool_result")) {
              throw new Error("The last message must contain only tool_result content if any is present");
            }
            if (!hasPreviousToolUse) {
              throw new Error("tool_result blocks are not matching any tool_use from the previous message");
            }
          }
          if (hasPreviousToolUse) {
            const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id));
            const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId));
            if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id2) => toolResultIds.has(id2))) {
              throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match");
            }
          }
        }
        if (params.tools) {
          return this.request({ method: "sampling/createMessage", params }, CreateMessageResultWithToolsSchema, options);
        }
        return this.request({ method: "sampling/createMessage", params }, CreateMessageResultSchema, options);
      });
    }
    /**
     * Creates an elicitation request for the given parameters.
     * For backwards compatibility, `mode` may be omitted for form requests and will default to `'form'`.
     * @param params The parameters for the elicitation request.
     * @param options Optional request options.
     * @returns The result of the elicitation request.
     */
    elicitInput(params, options) {
      return __async(this, null, function* () {
        var _a3, _b2, _c2, _d2, _e;
        const mode = (_a3 = params.mode) != null ? _a3 : "form";
        switch (mode) {
          case "url": {
            if (!((_c2 = (_b2 = this._clientCapabilities) == null ? void 0 : _b2.elicitation) == null ? void 0 : _c2.url)) {
              throw new Error("Client does not support url elicitation.");
            }
            const urlParams = params;
            return this.request({ method: "elicitation/create", params: urlParams }, ElicitResultSchema, options);
          }
          case "form": {
            if (!((_e = (_d2 = this._clientCapabilities) == null ? void 0 : _d2.elicitation) == null ? void 0 : _e.form)) {
              throw new Error("Client does not support form elicitation.");
            }
            const formParams = params.mode === "form" ? params : __spreadProps(__spreadValues({}, params), { mode: "form" });
            const result2 = yield this.request({ method: "elicitation/create", params: formParams }, ElicitResultSchema, options);
            if (result2.action === "accept" && result2.content && formParams.requestedSchema) {
              try {
                const validator = this._jsonSchemaValidator.getValidator(formParams.requestedSchema);
                const validationResult = validator(result2.content);
                if (!validationResult.valid) {
                  throw new McpError(ErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`);
                }
              } catch (error2) {
                if (error2 instanceof McpError) {
                  throw error2;
                }
                throw new McpError(ErrorCode.InternalError, `Error validating elicitation response: ${error2 instanceof Error ? error2.message : String(error2)}`);
              }
            }
            return result2;
          }
        }
      });
    }
    /**
     * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete`
     * notification for the specified elicitation ID.
     *
     * @param elicitationId The ID of the elicitation to mark as complete.
     * @param options Optional notification options. Useful when the completion notification should be related to a prior request.
     * @returns A function that emits the completion notification when awaited.
     */
    createElicitationCompletionNotifier(elicitationId, options) {
      var _a3, _b2;
      if (!((_b2 = (_a3 = this._clientCapabilities) == null ? void 0 : _a3.elicitation) == null ? void 0 : _b2.url)) {
        throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");
      }
      return () => this.notification({
        method: "notifications/elicitation/complete",
        params: {
          elicitationId
        }
      }, options);
    }
    listRoots(params, options) {
      return __async(this, null, function* () {
        return this.request({ method: "roots/list", params }, ListRootsResultSchema, options);
      });
    }
    /**
     * Sends a logging message to the client, if connected.
     * Note: You only need to send the parameters object, not the entire JSON RPC message
     * @see LoggingMessageNotification
     * @param params
     * @param sessionId optional for stateless and backward compatibility
     */
    sendLoggingMessage(params, sessionId) {
      return __async(this, null, function* () {
        if (this._capabilities.logging) {
          if (!this.isMessageIgnored(params.level, sessionId)) {
            return this.notification({ method: "notifications/message", params });
          }
        }
      });
    }
    sendResourceUpdated(params) {
      return __async(this, null, function* () {
        return this.notification({
          method: "notifications/resources/updated",
          params
        });
      });
    }
    sendResourceListChanged() {
      return __async(this, null, function* () {
        return this.notification({
          method: "notifications/resources/list_changed"
        });
      });
    }
    sendToolListChanged() {
      return __async(this, null, function* () {
        return this.notification({ method: "notifications/tools/list_changed" });
      });
    }
    sendPromptListChanged() {
      return __async(this, null, function* () {
        return this.notification({ method: "notifications/prompts/list_changed" });
      });
    }
  }
  var TOOL_NAMES = {
    BROWSER: {
      GET_WINDOWS_AND_TABS: "get_windows_and_tabs",
      SEARCH_TABS_CONTENT: "search_tabs_content",
      NAVIGATE: "chrome_navigate",
      SCREENSHOT: "chrome_screenshot",
      CLOSE_TABS: "chrome_close_tabs",
      GO_BACK_OR_FORWARD: "chrome_go_back_or_forward",
      WEB_FETCHER: "chrome_get_web_content",
      CLICK: "chrome_click_element",
      FILL: "chrome_fill_or_select",
      GET_INTERACTIVE_ELEMENTS: "chrome_get_interactive_elements",
      NETWORK_CAPTURE_START: "chrome_network_capture_start",
      NETWORK_CAPTURE_STOP: "chrome_network_capture_stop",
      NETWORK_REQUEST: "chrome_network_request",
      BACKGROUND_NETWORK_REQUEST: "chrome_background_network_request",
      NETWORK_DEBUGGER_START: "chrome_network_debugger_start",
      NETWORK_DEBUGGER_STOP: "chrome_network_debugger_stop",
      KEYBOARD: "chrome_keyboard",
      INJECT_SCRIPT: "chrome_inject_script",
      EXECUTE_SCRIPT: "chrome_execute_script",
      SEND_COMMAND_TO_INJECT_SCRIPT: "chrome_send_command_to_inject_script",
      CONSOLE: "chrome_console",
      SCROLL: "chrome_scroll",
      SCROLL_INTO_VIEW: "chrome_scroll_into_view",
      PAGE_PROTECTION_ENABLE: "chrome_page_protection_enable",
      PAGE_PROTECTION_DISABLE: "chrome_page_protection_disable",
      PAGE_PROTECTION_STATUS: "chrome_page_protection_status",
      HIGHLIGHT_ELEMENTS: "chrome_highlight_elements",
      REMOVE_HIGHLIGHTS: "chrome_remove_highlights",
      INPUT_UPLOAD_FILE: "chrome_input_upload_file",
      WAIT_FOR_ELEMENT: "chrome_wait_for_element",
      SCREENSHOT_WITH_HIGHLIGHTS: "chrome_screenshot_with_highlights",
      ACCESSIBILITY_SNAPSHOT: "chrome_accessibility_snapshot"
      // CDP 版本 - 获取页面可访问性树快照
    }
  };
  var TOOL_SCHEMAS$1 = [
    {
      name: TOOL_NAMES.BROWSER.GET_WINDOWS_AND_TABS,
      description: "Get all currently open browser windows and tabs",
      inputSchema: {
        type: "object",
        properties: {},
        required: []
      }
    },
    {
      name: TOOL_NAMES.BROWSER.NAVIGATE,
      description: "Navigate to a URL or refresh the current tab",
      inputSchema: {
        type: "object",
        properties: {
          url: { type: "string", description: "URL to navigate to the website specified" },
          newWindow: {
            type: "boolean",
            description: "Create a new window to navigate to the URL or not. Defaults to false"
          },
          width: { type: "number", description: "Viewport width in pixels (default: 1280)" },
          height: { type: "number", description: "Viewport height in pixels (default: 720)" },
          refresh: {
            type: "boolean",
            description: "Refresh the current active tab instead of navigating to a URL. When true, the url parameter is ignored. Defaults to false"
          },
          skipDuplicateCheck: {
            type: "boolean",
            description: "Skip duplicate tab check. When true, always create a new tab even if the URL is already open. Defaults to false"
          }
        },
        required: []
      }
    },
    {
      name: TOOL_NAMES.BROWSER.SCREENSHOT,
      description: "Take a screenshot of the current page or a specific element(if you want to see the page, recommend to use chrome_get_web_content first)",
      inputSchema: {
        type: "object",
        properties: {
          selector: { type: "string", description: "CSS selector for element to screenshot" },
          width: { type: "number", description: "Width in pixels (default: 800)" },
          height: { type: "number", description: "Height in pixels (default: 600)" },
          storeBase64: {
            type: "boolean",
            description: "return screenshot in base64 format (default: false) if you want to see the page, recommend set this to be true"
          },
          uploadImage: {
            type: "boolean",
            description: "Upload screenshot to server and return access URL (default: true if storeBase64 is false)"
          },
          fullPage: {
            type: "boolean",
            description: "Capture screenshot of the entire page by scrolling and stitching. Use only when you need the complete page content as it can be resource-intensive for long pages (default: false)"
          },
          maxHeight: {
            type: "number",
            description: "Maximum height for full page capture in pixels (default: 50000)"
          },
          tabId: {
            type: "number",
            description: "Target tab ID (optional, defaults to active tab)"
          }
        },
        required: []
      }
    },
    {
      name: TOOL_NAMES.BROWSER.CLOSE_TABS,
      description: "Close one or more browser tabs. If closing would result in an empty window, a new blank tab will be automatically created to prevent the window from closing.",
      inputSchema: {
        type: "object",
        properties: {
          tabIds: {
            type: "array",
            items: { type: "number" },
            description: "Array of tab IDs to close. If not provided, will close the active tab."
          },
          url: {
            type: "string",
            description: "Close tabs matching this URL. Can be used instead of tabIds."
          }
        },
        required: []
      }
    },
    {
      name: TOOL_NAMES.BROWSER.GO_BACK_OR_FORWARD,
      description: "Navigate back or forward in browser history",
      inputSchema: {
        type: "object",
        properties: {
          isForward: {
            type: "boolean",
            description: "Go forward in history if true, go back if false (default: false)"
          }
        },
        required: []
      }
    },
    {
      name: TOOL_NAMES.BROWSER.WEB_FETCHER,
      description: "Fetch content from a web page",
      inputSchema: {
        type: "object",
        properties: {
          url: {
            type: "string",
            description: "URL to fetch content from. If not provided, uses the current active tab"
          },
          htmlContent: {
            type: "boolean",
            description: "Get the visible HTML content of the page. If true, textContent will be ignored (default: false)"
          },
          textContent: {
            type: "boolean",
            description: "Get the visible text content of the page with metadata. Ignored if htmlContent is true (default: true)"
          },
          selector: {
            type: "string",
            description: "CSS selector to get content from a specific element. If provided, only content from this element will be returned"
          },
          skipClean: {
            type: "boolean",
            description: "Skip HTML cleaning when htmlContent is true. Returns raw HTML with styles, scripts, and other elements intact. Only effective when htmlContent is true (default: false)"
          },
          tabId: {
            type: "number",
            description: "Target tab ID (optional, defaults to active tab)"
          },
          uploadHtml: {
            type: "boolean",
            description: "Upload HTML content to object storage and return an accessible URL (default: false)"
          }
        },
        required: []
      }
    },
    {
      name: TOOL_NAMES.BROWSER.CLICK,
      description: "Click on an element in the current page or at specific coordinates",
      inputSchema: {
        type: "object",
        properties: {
          selector: {
            type: "string",
            description: "CSS selector for the element to click. Either selector or coordinates must be provided. if coordinates are not provided, the selector must be provided."
          },
          coordinates: {
            type: "object",
            description: "Coordinates to click at (relative to viewport). If provided, takes precedence over selector.",
            properties: {
              x: {
                type: "number",
                description: "X coordinate relative to the viewport"
              },
              y: {
                type: "number",
                description: "Y coordinate relative to the viewport"
              }
            },
            required: ["x", "y"]
          },
          waitForNavigation: {
            type: "boolean",
            description: "Wait for page navigation to complete after click (default: false)"
          },
          timeout: {
            type: "number",
            description: "Timeout in milliseconds for waiting for the element or navigation (default: 5000)"
          },
          tabId: {
            type: "number",
            description: "Target tab ID (optional, defaults to active tab)"
          }
        },
        required: []
      }
    },
    {
      name: TOOL_NAMES.BROWSER.FILL,
      description: "Fill a form element or select an option with the specified value",
      inputSchema: {
        type: "object",
        properties: {
          selector: {
            type: "string",
            description: "CSS selector for the input element to fill or select"
          },
          value: {
            type: "string",
            description: "Value to fill or select into the element"
          },
          tabId: {
            type: "number",
            description: "Target tab ID (optional, defaults to active tab)"
          }
        },
        required: ["selector", "value"]
      }
    },
    {
      name: TOOL_NAMES.BROWSER.GET_INTERACTIVE_ELEMENTS,
      description: "⚠️ LEGACY FALLBACK - 优先使用 chrome_get_interactive_elements_cdp。此工具需要激活页面，仅在 CDP 版本不可用时使用。Get interactive elements from the current page (requires page activation)",
      inputSchema: {
        type: "object",
        properties: {
          textQuery: {
            type: "string",
            description: "Text to search for within interactive elements (fuzzy search)"
          },
          selector: {
            type: "string",
            description: "CSS selector to filter interactive elements. Takes precedence over textQuery if both are provided."
          },
          includeCoordinates: {
            type: "boolean",
            description: "Include element coordinates in the response (default: true)"
          },
          tabId: {
            type: "number",
            description: "Target tab ID (optional, defaults to active tab)"
          }
        },
        required: []
      }
    },
    {
      name: TOOL_NAMES.BROWSER.NETWORK_REQUEST,
      description: "Send a network request from the browser with cookies and other browser context",
      inputSchema: {
        type: "object",
        properties: {
          url: {
            type: "string",
            description: "URL to send the request to"
          },
          method: {
            type: "string",
            description: "HTTP method to use (default: GET)"
          },
          headers: {
            type: "object",
            description: "Headers to include in the request"
          },
          body: {
            type: "string",
            description: "Body of the request (for POST, PUT, etc.)"
          },
          timeout: {
            type: "number",
            description: "Timeout in milliseconds (default: 30000)"
          }
        },
        required: ["url"]
      }
    },
    {
      name: TOOL_NAMES.BROWSER.BACKGROUND_NETWORK_REQUEST,
      description: "Send a network request in the background without requiring an active tab or content script",
      inputSchema: {
        type: "object",
        properties: {
          url: {
            type: "string",
            description: "URL to send the request to"
          },
          method: {
            type: "string",
            description: "HTTP method to use (default: GET)"
          },
          headers: {
            type: "object",
            description: "Headers to include in the request"
          },
          body: {
            type: "string",
            description: "Body of the request (for POST, PUT, etc.)"
          },
          timeout: {
            type: "number",
            description: "Timeout in milliseconds (default: 30000)"
          }
        },
        required: ["url"]
      }
    },
    {
      name: TOOL_NAMES.BROWSER.NETWORK_DEBUGGER_START,
      description: "Start capturing network requests from a web page using Chrome Debugger API（with responseBody）",
      inputSchema: {
        type: "object",
        properties: {
          url: {
            type: "string",
            description: "URL to capture network requests from. If not provided, uses the current active tab"
          }
        },
        required: []
      }
    },
    {
      name: TOOL_NAMES.BROWSER.NETWORK_DEBUGGER_STOP,
      description: "Stop capturing network requests using Chrome Debugger API and return the captured data",
      inputSchema: {
        type: "object",
        properties: {},
        required: []
      }
    },
    {
      name: TOOL_NAMES.BROWSER.NETWORK_CAPTURE_START,
      description: "Start capturing network requests from a web page using Chrome webRequest API(without responseBody)",
      inputSchema: {
        type: "object",
        properties: {
          url: {
            type: "string",
            description: "URL to capture network requests from. If not provided, uses the current active tab"
          }
        },
        required: []
      }
    },
    {
      name: TOOL_NAMES.BROWSER.NETWORK_CAPTURE_STOP,
      description: "Stop capturing network requests using webRequest API and return the captured data",
      inputSchema: {
        type: "object",
        properties: {},
        required: []
      }
    },
    {
      name: TOOL_NAMES.BROWSER.KEYBOARD,
      description: "Simulate keyboard events in the browser",
      inputSchema: {
        type: "object",
        properties: {
          keys: {
            type: "string",
            description: 'Keys to simulate (e.g., "Enter", "Ctrl+C", "A,B,C" for sequence)'
          },
          selector: {
            type: "string",
            description: "CSS selector for the element to send keyboard events to (optional, defaults to active element)"
          },
          delay: {
            type: "number",
            description: "Delay between key sequences in milliseconds (optional, default: 0)"
          }
        },
        required: ["keys"]
      }
    },
    // {
    //   name: TOOL_NAMES.BROWSER.HISTORY,
    //   description: 'Retrieve and search browsing history from Chrome',
    //   inputSchema: {
    //     type: 'object',
    //     properties: {
    //       text: {
    //         type: 'string',
    //         description:
    //           'Text to search for in history URLs and titles. Leave empty to retrieve all history entries within the time range.',
    //       },
    //       startTime: {
    //         type: 'string',
    //         description:
    //           'Start time as a date string. Supports ISO format (e.g., "2023-10-01", "2023-10-01T14:30:00"), relative times (e.g., "1 day ago", "2 weeks ago", "3 months ago", "1 year ago"), and special keywords ("now", "today", "yesterday"). Default: 24 hours ago',
    //       },
    //       endTime: {
    //         type: 'string',
    //         description:
    //           'End time as a date string. Supports ISO format (e.g., "2023-10-31", "2023-10-31T14:30:00"), relative times (e.g., "1 day ago", "2 weeks ago", "3 months ago", "1 year ago"), and special keywords ("now", "today", "yesterday"). Default: current time',
    //       },
    //       maxResults: {
    //         type: 'number',
    //         description:
    //           'Maximum number of history entries to return. Use this to limit results for performance or to focus on the most relevant entries. (default: 100)',
    //       },
    //       excludeCurrentTabs: {
    //         type: 'boolean',
    //         description:
    //           "When set to true, filters out URLs that are currently open in any browser tab. Useful for finding pages you've visited but don't have open anymore. (default: false)",
    //       },
    //     },
    //     required: [],
    //   },
    // },
    // {
    //   name: TOOL_NAMES.BROWSER.BOOKMARK_SEARCH,
    //   description: 'Search Chrome bookmarks by title and URL',
    //   inputSchema: {
    //     type: 'object',
    //     properties: {
    //       query: {
    //         type: 'string',
    //         description:
    //           'Search query to match against bookmark titles and URLs. Leave empty to retrieve all bookmarks.',
    //       },
    //       maxResults: {
    //         type: 'number',
    //         description: 'Maximum number of bookmarks to return (default: 50)',
    //       },
    //       folderPath: {
    //         type: 'string',
    //         description:
    //           'Optional folder path or ID to limit search to a specific bookmark folder. Can be a path string (e.g., "Work/Projects") or a folder ID.',
    //       },
    //     },
    //     required: [],
    //   },
    // },
    // {
    //   name: TOOL_NAMES.BROWSER.BOOKMARK_ADD,
    //   description: 'Add a new bookmark to Chrome',
    //   inputSchema: {
    //     type: 'object',
    //     properties: {
    //       url: {
    //         type: 'string',
    //         description: 'URL to bookmark. If not provided, uses the current active tab URL.',
    //       },
    //       title: {
    //         type: 'string',
    //         description: 'Title for the bookmark. If not provided, uses the page title from the URL.',
    //       },
    //       parentId: {
    //         type: 'string',
    //         description:
    //           'Parent folder path or ID to add the bookmark to. Can be a path string (e.g., "Work/Projects") or a folder ID. If not provided, adds to the "Bookmarks Bar" folder.',
    //       },
    //       createFolder: {
    //         type: 'boolean',
    //         description: 'Whether to create the parent folder if it does not exist (default: false)',
    //       },
    //     },
    //     required: [],
    //   },
    // },
    // {
    //   name: TOOL_NAMES.BROWSER.BOOKMARK_DELETE,
    //   description: 'Delete a bookmark from Chrome',
    //   inputSchema: {
    //     type: 'object',
    //     properties: {
    //       bookmarkId: {
    //         type: 'string',
    //         description: 'ID of the bookmark to delete. Either bookmarkId or url must be provided.',
    //       },
    //       url: {
    //         type: 'string',
    //         description: 'URL of the bookmark to delete. Used if bookmarkId is not provided.',
    //       },
    //       title: {
    //         type: 'string',
    //         description: 'Title of the bookmark to help with matching when deleting by URL.',
    //       },
    //     },
    //     required: [],
    //   },
    // },
    {
      name: TOOL_NAMES.BROWSER.SEARCH_TABS_CONTENT,
      description: "search for related content from the currently open tab and return the corresponding web pages.",
      inputSchema: {
        type: "object",
        properties: {
          query: {
            type: "string",
            description: "the query to search for related content."
          }
        },
        required: ["query"]
      }
    },
    {
      name: TOOL_NAMES.BROWSER.INJECT_SCRIPT,
      description: "inject the user-specified content script into the webpage. By default, inject into the currently active tab",
      inputSchema: {
        type: "object",
        properties: {
          url: {
            type: "string",
            description: "If a URL is specified, inject the script into the webpage corresponding to the URL."
          },
          type: {
            type: "string",
            description: "the javaScript world for a script to execute within. must be ISOLATED or MAIN"
          },
          jsScript: {
            type: "string",
            description: "the content script to inject"
          }
        },
        required: ["type", "jsScript"]
      }
    },
    {
      name: TOOL_NAMES.BROWSER.SEND_COMMAND_TO_INJECT_SCRIPT,
      description: "if the script injected using chrome_inject_script listens for user-defined events, this tool can be used to trigger those events",
      inputSchema: {
        type: "object",
        properties: {
          tabId: {
            type: "number",
            description: "the tab where you previously injected the script(if not provided,  use the currently active tab)"
          },
          eventName: {
            type: "string",
            description: "the eventName your injected content script listen for"
          },
          payload: {
            type: "string",
            description: "the payload passed to event, must be a json string"
          }
        },
        required: ["eventName"]
      }
    },
    {
      name: TOOL_NAMES.BROWSER.CONSOLE,
      description: "Capture and retrieve all console output from the current active browser tab/page. This captures console messages that existed before the tool was called.",
      inputSchema: {
        type: "object",
        properties: {
          url: {
            type: "string",
            description: "URL to navigate to and capture console from. If not provided, uses the current active tab"
          },
          includeExceptions: {
            type: "boolean",
            description: "Include uncaught exceptions in the output (default: true)"
          },
          maxMessages: {
            type: "number",
            description: "Maximum number of console messages to capture (default: 100)"
          }
        },
        required: []
      }
    },
    {
      name: TOOL_NAMES.BROWSER.SCROLL,
      description: "Scroll the current page or a specific element in the browser",
      inputSchema: {
        type: "object",
        properties: {
          direction: {
            type: "string",
            enum: ["up", "down", "left", "right"],
            description: "Direction to scroll (default: down)"
          },
          distance: {
            type: "number",
            description: "Distance to scroll in pixels (default: 300)"
          },
          coordinates: {
            type: "object",
            description: "Coordinates of the area to scroll (relative to viewport)",
            properties: {
              x: {
                type: "number",
                description: "X coordinate relative to the viewport"
              },
              y: {
                type: "number",
                description: "Y coordinate relative to the viewport"
              }
            },
            required: ["x", "y"]
          },
          selector: {
            type: "string",
            description: "CSS selector for the element to scroll. Takes precedence over coordinates."
          },
          smooth: {
            type: "boolean",
            description: "Whether to use smooth scrolling (default: true)"
          },
          timeout: {
            type: "number",
            description: "Timeout in milliseconds for the scroll operation (default: 3000)"
          },
          tabId: {
            type: "number",
            description: "Target tab ID (optional, defaults to active tab)"
          }
        },
        required: []
      }
    },
    // {
    //   name: TOOL_NAMES.BROWSER.SCROLL_CDP,
    //   description: 'Scroll the current page or a specific element in the browser using CDP',
    //   inputSchema: {
    //     type: 'object',
    //     properties: {
    //       direction: {
    //         type: 'string',
    //         enum: ['up', 'down', 'left', 'right'],
    //         description: 'Direction to scroll (default: down)',
    //       },
    //       distance: {
    //         type: 'number',
    //         description: 'Distance to scroll in pixels (default: 300)',
    //       },
    //       coordinates: {
    //         type: 'object',
    //         description: 'Coordinates of the area to scroll (relative to viewport)',
    //         properties: {
    //           x: {
    //             type: 'number',
    //             description: 'X coordinate relative to the viewport',
    //           },
    //           y: {
    //             type: 'number',
    //             description: 'Y coordinate relative to the viewport',
    //           },
    //         },
    //         required: ['x', 'y'],
    //       },
    //       selector: {
    //         type: 'string',
    //         description: 'CSS selector for the element to scroll. Takes precedence over coordinates.',
    //       },
    //       smooth: {
    //         type: 'boolean',
    //         description: 'Whether to use smooth scrolling (default: true)',
    //       },
    //       timeout: {
    //         type: 'number',
    //         description: 'Timeout in milliseconds for the scroll operation (default: 3000)',
    //       },
    //       tabId: {
    //         type: 'number',
    //         description: 'Target tab ID (optional, defaults to active tab)',
    //       },
    //     },
    //     required: [],
    //   },
    // },
    {
      name: TOOL_NAMES.BROWSER.PAGE_PROTECTION_ENABLE,
      description: "Enable page protection by creating an overlay that prevents user interactions and automatically enables close warning",
      inputSchema: {
        type: "object",
        properties: {
          tabId: {
            type: "number",
            description: "Target tab ID (optional, defaults to active tab)"
          }
        },
        required: []
      }
    },
    {
      name: TOOL_NAMES.BROWSER.PAGE_PROTECTION_DISABLE,
      description: "Disable page protection by removing the overlay and automatically disabling close warning",
      inputSchema: {
        type: "object",
        properties: {
          tabId: {
            type: "number",
            description: "Target tab ID (optional, defaults to active tab)"
          }
        },
        required: []
      }
    },
    {
      name: TOOL_NAMES.BROWSER.PAGE_PROTECTION_STATUS,
      description: "Check the current page protection status for a tab",
      inputSchema: {
        type: "object",
        properties: {
          tabId: {
            type: "number",
            description: "Target tab ID (optional, defaults to active tab)"
          }
        },
        required: []
      }
    },
    {
      name: TOOL_NAMES.BROWSER.HIGHLIGHT_ELEMENTS,
      description: "Highlight interactive elements on the current page with visual indicators and confidence levels",
      inputSchema: {
        type: "object",
        properties: {
          selector: {
            type: "string",
            description: "CSS selector to highlight specific elements. If not provided, highlights all interactive elements"
          },
          tabId: {
            type: "number",
            description: "Target tab ID (optional, defaults to active tab)"
          }
        },
        required: []
      }
    },
    {
      name: TOOL_NAMES.BROWSER.REMOVE_HIGHLIGHTS,
      description: "Remove all highlighting elements from the current page",
      inputSchema: {
        type: "object",
        properties: {
          tabId: {
            type: "number",
            description: "Target tab ID (optional, defaults to active tab)"
          }
        },
        required: []
      }
    },
    {
      name: TOOL_NAMES.BROWSER.INPUT_UPLOAD_FILE,
      description: "Upload files to web page file input elements from various sources (URL, base64)",
      inputSchema: {
        type: "object",
        properties: {
          sourceType: {
            type: "string",
            enum: ["url", "base64"],
            description: "Source type of the file: url (from web), base64 (encoded data)"
          },
          url: {
            type: "string",
            description: 'URL of the file to upload (required when sourceType is "url")'
          },
          base64Data: {
            type: "string",
            description: 'Base64 encoded file data (required when sourceType is "base64")'
          },
          filename: {
            type: "string",
            description: "Name of the file (optional, will be inferred from URL or default)"
          },
          mimeType: {
            type: "string",
            description: "MIME type of the file (optional, will be inferred from filename or content)"
          },
          inputSelector: {
            type: "string",
            description: 'CSS selector for the file input element (default: input[type="file"])'
          },
          multiple: {
            type: "boolean",
            description: "Whether to upload multiple files (default: false)"
          },
          files: {
            type: "array",
            description: "Array of files for multiple upload (used when multiple is true)",
            items: {
              type: "object",
              properties: {
                sourceType: {
                  type: "string",
                  enum: ["url", "base64"],
                  description: "Source type: url or base64"
                },
                url: {
                  type: "string",
                  description: "URL of the file"
                },
                base64Data: {
                  type: "string",
                  description: "Base64 encoded file data"
                },
                filename: {
                  type: "string",
                  description: "Name of the file"
                },
                mimeType: {
                  type: "string",
                  description: "MIME type of the file"
                }
              }
            }
          },
          dropZoneSelector: {
            type: "string",
            description: "CSS selector for drag-and-drop zone (alternative to input selector)"
          },
          waitForComplete: {
            type: "boolean",
            description: "Wait for upload completion and monitor status (default: false)"
          },
          successSelectors: {
            type: "array",
            items: { type: "string" },
            description: "CSS selectors to detect successful upload (used with waitForComplete)"
          },
          errorSelectors: {
            type: "array",
            items: { type: "string" },
            description: "CSS selectors to detect upload errors (used with waitForComplete)"
          },
          timeout: {
            type: "number",
            description: "Timeout in milliseconds for upload operations (default: 30000)"
          },
          tabId: {
            type: "number",
            description: "Target tab ID (optional, defaults to active tab)"
          }
        },
        required: ["sourceType"]
      }
    },
    {
      name: TOOL_NAMES.BROWSER.SCROLL_INTO_VIEW,
      description: "Scroll a specific element into view within the viewport",
      inputSchema: {
        type: "object",
        properties: {
          selector: {
            type: "string",
            description: "CSS selector for the element to scroll into view"
          },
          behavior: {
            type: "string",
            enum: ["auto", "smooth"],
            description: "Scroll behavior: auto for instant scrolling, smooth for animated scrolling (default: smooth)"
          },
          block: {
            type: "string",
            enum: ["start", "center", "end", "nearest"],
            description: "Vertical alignment of the element within the viewport (default: center)"
          },
          inline: {
            type: "string",
            enum: ["start", "center", "end", "nearest"],
            description: "Horizontal alignment of the element within the viewport (default: center)"
          },
          timeout: {
            type: "number",
            description: "Timeout in milliseconds for the scroll operation (default: 3000)"
          },
          tabId: {
            type: "number",
            description: "Target tab ID (optional, defaults to active tab)"
          }
        },
        required: ["selector"]
      }
    },
    {
      name: TOOL_NAMES.BROWSER.WAIT_FOR_ELEMENT,
      description: "Wait for an element to appear on the page within a specified timeout period",
      inputSchema: {
        type: "object",
        properties: {
          selector: {
            type: "string",
            description: "CSS selector for the element to wait for"
          },
          timeout: {
            type: "number",
            description: "Timeout in milliseconds to wait for the element (default: 10000)"
          },
          visible: {
            type: "boolean",
            description: "Whether the element should be visible (not just present in DOM) (default: true)"
          },
          tabId: {
            type: "number",
            description: "Target tab ID (optional, defaults to active tab)"
          }
        },
        required: ["selector"]
      }
    },
    {
      name: TOOL_NAMES.BROWSER.SCREENSHOT_WITH_HIGHLIGHTS,
      description: "Highlight interactive elements on the page and capture a screenshot, then upload both the element details JSON and screenshot to the server. Returns two file URLs: 1) JSON file containing highlighted element details 2) Screenshot image. The index field in JSON elements array corresponds to the numbered labels on the screenshot, enabling precise element identification.",
      inputSchema: {
        type: "object",
        properties: {
          name: {
            type: "string",
            description: 'Filename prefix for the uploaded files (default: "highlights")'
          },
          selector: {
            type: "string",
            description: "CSS selector to filter which elements to highlight. If not provided, highlights all interactive elements"
          },
          highlightDelay: {
            type: "number",
            description: "Time in milliseconds to wait after highlighting before capturing screenshot, ensuring complete rendering (default: 500)"
          },
          tabId: {
            type: "number",
            description: "Target tab ID (optional, defaults to active tab)"
          }
        },
        required: []
      }
    },
    {
      name: TOOL_NAMES.BROWSER.EXECUTE_SCRIPT,
      description: "Execute a JavaScript function in the browser and synchronously get the result. Unlike chrome_inject_script (which injects persistent code), this tool runs one-time scripts and immediately returns values. Supports both ISOLATED and MAIN execution worlds.",
      inputSchema: {
        type: "object",
        properties: {
          jsScript: {
            type: "string",
            description: 'JavaScript function body as a string, e.g., "() => document.title" or "(a, b) => a + b"'
          },
          args: {
            type: "array",
            description: "Arguments to pass to the function (optional, default: [])",
            items: {}
          },
          world: {
            type: "string",
            enum: ["ISOLATED", "MAIN"],
            description: "Execution context: ISOLATED (default, safer, extension context) or MAIN (page context, can access page variables)"
          },
          tabId: {
            type: "number",
            description: "Target tab ID (optional, defaults to active tab)"
          },
          timeout: {
            type: "number",
            description: "Timeout in milliseconds (optional, default: 5000)"
          }
        },
        required: ["jsScript"]
      }
    }
  ];
  var registeredTools = /* @__PURE__ */ new Map();
  function registerToolForAutoSchema(tool) {
    if (!tool.name) {
      console.warn("Tool missing name property, skipping registration");
      return;
    }
    registeredTools.set(tool.name, tool);
    console.log(`[Schema Generator] Registered tool for auto-generation: ${tool.name}`);
  }
  function getToolSchemas() {
    const schemaMap = /* @__PURE__ */ new Map();
    const _manualMap = /* @__PURE__ */ new Map();
    for (const schema of TOOL_SCHEMAS$1) {
      _manualMap.set(schema.name, schema);
    }
    for (const [toolName, tool] of registeredTools.entries()) {
      try {
        if (tool.toJSONSchema) {
          const autoSchema = tool.toJSONSchema();
          schemaMap.set(toolName, autoSchema);
          console.log(`[Schema Generator] Using auto-generated schema for: ${toolName}`);
        } else {
          const manualSchema = _manualMap.get(toolName);
          if (manualSchema) {
            schemaMap.set(toolName, manualSchema);
          } else {
            console.log(
              `[Schema Generator] Tool ${toolName} doesn't support auto-generation, using manual schema`
            );
          }
        }
      } catch (error2) {
        console.warn(
          `[Schema Generator] Failed to auto-generate schema for ${toolName}, using manual fallback:`,
          error2
        );
      }
    }
    return Array.from(schemaMap.values());
  }
  const createErrorResponse = (message = "Unknown error, please try again") => {
    return {
      content: [
        {
          type: "text",
          text: message
        }
      ],
      isError: true
    };
  };
  const TIMEOUTS = {
    DEFAULT_WAIT: 1e3,
    KEYBOARD_DELAY: 50
  };
  const LIMITS$1 = {
    MAX_NETWORK_REQUESTS: 100
  };
  const ERROR_MESSAGES = {
    NATIVE_CONNECTION_FAILED: "Failed to connect to native host",
    NATIVE_DISCONNECTED: "Native connection disconnected",
    SERVER_STATUS_LOAD_FAILED: "Failed to load server status",
    SERVER_STATUS_SAVE_FAILED: "Failed to save server status",
    TOOL_EXECUTION_FAILED: "Tool execution failed",
    INVALID_PARAMETERS: "Invalid parameters provided",
    PERMISSION_DENIED: "Permission denied",
    TAB_NOT_FOUND: "Tab not found",
    ELEMENT_NOT_FOUND: "Element not found",
    NETWORK_ERROR: "Network error occurred"
  };
  const NETWORK_FILTERS = {
    EXCLUDED_DOMAINS: [
      "google-analytics.com",
      "googletagmanager.com",
      "facebook.com",
      "doubleclick.net",
      "googlesyndication.com"
    ]
  };
  var ExecutionWorld = /* @__PURE__ */ ((ExecutionWorld2) => {
    ExecutionWorld2["ISOLATED"] = "ISOLATED";
    ExecutionWorld2["MAIN"] = "MAIN";
    return ExecutionWorld2;
  })(ExecutionWorld || {});
  const IMAGE_TYPE = "base64";
  var ToolCategory = /* @__PURE__ */ ((ToolCategory2) => {
    ToolCategory2["INPUT"] = "input";
    ToolCategory2["NAVIGATION"] = "navigation";
    ToolCategory2["EMULATION"] = "emulation";
    ToolCategory2["PERFORMANCE"] = "performance";
    ToolCategory2["NETWORK"] = "network";
    ToolCategory2["DEBUGGING"] = "debugging";
    return ToolCategory2;
  })(ToolCategory || {});
  const PING_TIMEOUT_MS = 300;
  const zodWithJSONSchema = zod;
  class BaseBrowserToolExecutor {
    constructor() {
      // Optional properties for backward compatibility
      __publicField2(this, "description");
      __publicField2(this, "annotations");
      __publicField2(this, "schema");
    }
    /**
     * Validate arguments against the schema
     * Returns validated and typed arguments, or a ToolResult with detailed error
     */
    validateArgs(args) {
      if (!this.schema) {
        return { success: true, data: args };
      }
      try {
        const validated = object(this.schema).parse(args);
        return { success: true, data: validated };
      } catch (err) {
        if (err instanceof ZodError) {
          const zodError = err;
          const errorDetails = zodError.issues.map((issue2) => {
            const field = issue2.path.join(".");
            const message = issue2.message;
            const received = issue2.code === "invalid_type" ? `received: ${issue2.received}` : "";
            return `  • Field "${field}": ${message}${received ? ` (${received})` : ""}`;
          }).join("\n");
          const errorMessage = `参数验证失败，请检查以下字段：
${errorDetails}

提示：请参考工具的 schema 定义确保所有必需字段都已提供且类型正确。`;
          return {
            success: false,
            error: error$J(errorMessage, "VALIDATION_ERROR", {
              input: args,
              validationErrors: zodError.issues,
              errorCount: zodError.issues.length
            })
          };
        }
        return {
          success: false,
          error: error$J(
            `参数验证时发生未知错误: ${err instanceof Error ? err.message : String(err)}`,
            "VALIDATION_ERROR"
          )
        };
      }
    }
    /**
     * Get tool metadata in Chrome MCP format
     */
    getMetadata() {
      return {
        name: this.name,
        description: this.description || `Tool: ${this.name}`,
        annotations: this.annotations || {
          category: ToolCategory.NAVIGATION,
          readOnlyHint: false
        },
        schema: this.schema || {}
      };
    }
    /**
     * Generate JSON Schema (MCP format) from Zod schema
     * Uses Zod 4's native z.toJSONSchema() function
     */
    toJSONSchema() {
      if (this.schema) {
        try {
          const zodSchema = object(this.schema);
          const jsonSchema2 = zodWithJSONSchema.toJSONSchema(zodSchema, {
            target: "draft-2020-12",
            // MCP 使用的 JSON Schema 版本
            io: "input"
            // 生成输入类型的 schema（不包含 transform 后的类型）
          });
          return {
            name: this.name,
            description: this.description || `Tool: ${this.name}`,
            inputSchema: jsonSchema2
          };
        } catch (error2) {
          console.warn(`Failed to auto-generate JSON Schema for ${this.name}:`, error2);
        }
      }
      const predefinedTool = TOOL_SCHEMAS$1.find((tool) => tool.name === this.name);
      if (predefinedTool) {
        return predefinedTool;
      }
      return {
        name: this.name,
        description: this.description || `Tool: ${this.name}`,
        inputSchema: {
          type: "object",
          properties: {},
          required: []
        }
      };
    }
    /**
     * Inject content script into tab
     */
    injectContentScript(tabId, files, injectImmediately = false, world = "ISOLATED") {
      return __async(this, null, function* () {
        console.log(`Injecting ${files.join(", ")} into tab ${tabId}`);
        try {
          const response = yield Promise.race([
            chrome.tabs.sendMessage(tabId, { action: `${this.name}_ping` }),
            new Promise(
              (_, reject) => setTimeout(
                () => reject(new Error(`${this.name} Ping action to tab ${tabId} timed out`)),
                PING_TIMEOUT_MS
              )
            )
          ]);
          if (response && response.status === "pong") {
            console.log(
              `pong received for action '${this.name}' in tab ${tabId}. Assuming script is active.`
            );
            return;
          } else {
            console.warn(`Unexpected ping response in tab ${tabId}:`, response);
          }
        } catch (error2) {
          console.error(
            `ping content script failed: ${error2 instanceof Error ? error2.message : String(error2)}`
          );
        }
        try {
          yield chrome.scripting.executeScript({
            target: { tabId },
            files,
            injectImmediately,
            world
          });
          console.log(`'${files.join(", ")}' injection successful for tab ${tabId}`);
        } catch (injectionError) {
          const errorMessage = injectionError instanceof Error ? injectionError.message : String(injectionError);
          console.error(
            `Content script '${files.join(", ")}' injection failed for tab ${tabId}: ${errorMessage}`
          );
          throw new Error(
            `${ERROR_MESSAGES.TOOL_EXECUTION_FAILED}: Failed to inject content script in tab ${tabId}: ${errorMessage}`
          );
        }
      });
    }
    /**
     * Send message to tab
     */
    sendMessageToTab(tabId, message) {
      return __async(this, null, function* () {
        try {
          const response = yield chrome.tabs.sendMessage(tabId, message);
          if (response && response.error) {
            throw new Error(String(response.error));
          }
          return response;
        } catch (error2) {
          const errorMessage = error2 instanceof Error ? error2.message : String(error2);
          console.error(
            `Error sending message to tab ${tabId} for action ${(message == null ? void 0 : message.action) || "unknown"}: ${errorMessage}`
          );
          if (error2 instanceof Error) {
            throw error2;
          }
          throw new Error(errorMessage);
        }
      });
    }
    /**
     * Send message to tab with timeout and retry mechanism
     */
    sendMessageToTabWithTimeout(tabId, message, timeoutMs = 5e3, retries = 2) {
      return __async(this, null, function* () {
        for (let attempt = 0; attempt <= retries; attempt++) {
          try {
            const response = yield Promise.race([
              this.sendMessageToTab(tabId, message),
              new Promise(
                (_, reject) => setTimeout(() => reject(new Error("Message timeout")), timeoutMs)
              )
            ]);
            return response;
          } catch (error2) {
            console.warn(`Message attempt ${attempt + 1} failed:`, error2);
            if (attempt === retries) {
              throw error2;
            }
            yield new Promise((resolve2) => setTimeout(resolve2, 1e3));
          }
        }
      });
    }
    /**
     * Classify communication error for better user feedback
     */
    classifyCommunicationError(error2) {
      const errorMessage = error2 instanceof Error ? error2.message : String(error2);
      if (errorMessage.includes("timeout")) {
        return "timeout";
      } else if (errorMessage.includes("Could not establish connection") || errorMessage.includes("Receiving end does not exist")) {
        return "script_missing";
      } else if (errorMessage.includes("Cannot access")) {
        return "permission_denied";
      } else if (errorMessage.includes("No tab with id")) {
        return "tab_not_found";
      } else {
        return "tab_unresponsive";
      }
    }
  }
  function disableTabProtection(tabId) {
    return __async(this, null, function* () {
      try {
        yield chrome.tabs.sendMessage(tabId, {
          action: "SET_PROTECTION_MODE",
          mode: "disabled"
        });
      } catch (error2) {
      }
    });
  }
  function safelyCloseTabs(tabIdsToClose, windowId) {
    return __async(this, null, function* () {
      try {
        const allTabsInWindow = yield chrome.tabs.query({ windowId });
        const remainingTabs = allTabsInWindow.filter((tab) => !tabIdsToClose.includes(tab.id));
        let protectionTriggered = false;
        if (remainingTabs.length === 0) {
          console.log(`Window ${windowId} would be empty after closing tabs, creating new tab`);
          yield chrome.tabs.create({
            windowId,
            url: "chrome://newtab",
            active: true
          });
          protectionTriggered = true;
        }
        yield chrome.tabs.remove(tabIdsToClose);
        return {
          closedCount: tabIdsToClose.length,
          protectionTriggered
        };
      } catch (error2) {
        console.error("Error in safelyCloseTabs:", error2);
        yield chrome.tabs.remove(tabIdsToClose);
        return {
          closedCount: tabIdsToClose.length,
          protectionTriggered: false
        };
      }
    });
  }
  class CloseTabsTool extends BaseBrowserToolExecutor {
    constructor() {
      super(...arguments);
      __publicField2(this, "name", TOOL_NAMES.BROWSER.CLOSE_TABS);
    }
    execute(args) {
      return __async(this, null, function* () {
        const { tabIds, url: url2 } = args;
        let urlPattern = url2;
        console.log(`Attempting to close tabs with options:`, args);
        try {
          if (urlPattern) {
            console.log(`Searching for tabs with URL: ${url2}`);
            if (!urlPattern.endsWith("/")) {
              urlPattern += "/*";
            }
            const tabs = yield chrome.tabs.query({ url: url2 });
            if (!tabs || tabs.length === 0) {
              console.log(`No tabs found with URL: ${url2}`);
              return {
                content: [
                  {
                    type: "text",
                    text: JSON.stringify({
                      success: false,
                      message: `No tabs found with URL: ${url2}`,
                      closedCount: 0
                    })
                  }
                ],
                isError: false
              };
            }
            console.log(`Found ${tabs.length} tabs with URL: ${url2}`);
            const tabIdsToClose = tabs.map((tab) => tab.id).filter((id2) => id2 !== void 0);
            if (tabIdsToClose.length === 0) {
              return createErrorResponse("Found tabs but could not get their IDs");
            }
            yield Promise.allSettled(tabIdsToClose.map(disableTabProtection));
            const firstTab = tabs[0];
            const windowId2 = firstTab.windowId;
            const result22 = yield safelyCloseTabs(tabIdsToClose, windowId2);
            return {
              content: [
                {
                  type: "text",
                  text: JSON.stringify({
                    success: true,
                    message: result22.protectionTriggered ? `Closed ${result22.closedCount} tabs (created new tab to prevent window closure)` : `Closed ${result22.closedCount} tabs with URL: ${url2}`,
                    closedCount: result22.closedCount,
                    closedTabIds: tabIdsToClose,
                    protectionTriggered: result22.protectionTriggered
                  })
                }
              ],
              isError: false
            };
          }
          if (tabIds && tabIds.length > 0) {
            console.log(`Closing tabs with IDs: ${tabIds.join(", ")}`);
            const existingTabs = yield Promise.all(
              tabIds.map((tabId) => __async(null, null, function* () {
                try {
                  return yield chrome.tabs.get(tabId);
                } catch (error2) {
                  console.warn(`Tab with ID ${tabId} not found`);
                  return null;
                }
              }))
            );
            const validTabIds = existingTabs.filter((tab) => tab !== null).map((tab) => tab.id).filter((id2) => id2 !== void 0);
            if (validTabIds.length === 0) {
              return {
                content: [
                  {
                    type: "text",
                    text: JSON.stringify({
                      success: false,
                      message: "None of the provided tab IDs exist",
                      closedCount: 0
                    })
                  }
                ],
                isError: false
              };
            }
            yield Promise.allSettled(validTabIds.map(disableTabProtection));
            const firstTab = yield chrome.tabs.get(validTabIds[0]);
            const windowId2 = firstTab.windowId;
            const result22 = yield safelyCloseTabs(validTabIds, windowId2);
            return {
              content: [
                {
                  type: "text",
                  text: JSON.stringify({
                    success: true,
                    message: result22.protectionTriggered ? `Closed ${result22.closedCount} tabs (created new tab to prevent window closure)` : `Closed ${result22.closedCount} tabs`,
                    closedCount: result22.closedCount,
                    closedTabIds: validTabIds,
                    invalidTabIds: tabIds.filter((id2) => !validTabIds.includes(id2)),
                    protectionTriggered: result22.protectionTriggered
                  })
                }
              ],
              isError: false
            };
          }
          console.log("No tabIds or URL provided, closing active tab");
          const [activeTab] = yield chrome.tabs.query({ active: true, currentWindow: true });
          if (!activeTab || !activeTab.id) {
            return createErrorResponse("No active tab found");
          }
          yield disableTabProtection(activeTab.id);
          const windowId = activeTab.windowId;
          const result2 = yield safelyCloseTabs([activeTab.id], windowId);
          return {
            content: [
              {
                type: "text",
                text: JSON.stringify({
                  success: true,
                  message: result2.protectionTriggered ? "Closed active tab (created new tab to prevent window closure)" : "Closed active tab",
                  closedCount: 1,
                  closedTabIds: [activeTab.id],
                  protectionTriggered: result2.protectionTriggered
                })
              }
            ],
            isError: false
          };
        } catch (error2) {
          console.error("Error in CloseTabsTool.execute:", error2);
          return createErrorResponse(
            `Error closing tabs: ${error2 instanceof Error ? error2.message : String(error2)}`
          );
        }
      });
    }
  }
  const closeTabsTool = new CloseTabsTool();
  class GoBackOrForwardTool extends BaseBrowserToolExecutor {
    constructor() {
      super(...arguments);
      __publicField2(this, "name", TOOL_NAMES.BROWSER.GO_BACK_OR_FORWARD);
    }
    execute(args) {
      return __async(this, null, function* () {
        const { isForward = false } = args;
        console.log(`Attempting to navigate ${isForward ? "forward" : "back"} in browser history`);
        try {
          const [activeTab] = yield chrome.tabs.query({ active: true, currentWindow: true });
          if (!activeTab || !activeTab.id) {
            return createErrorResponse("No active tab found");
          }
          if (isForward) {
            yield chrome.tabs.goForward(activeTab.id);
            console.log(`Navigated forward in tab ID: ${activeTab.id}`);
          } else {
            yield chrome.tabs.goBack(activeTab.id);
            console.log(`Navigated back in tab ID: ${activeTab.id}`);
          }
          const updatedTab = yield chrome.tabs.get(activeTab.id);
          return {
            content: [
              {
                type: "text",
                text: JSON.stringify({
                  success: true,
                  message: `Successfully navigated ${isForward ? "forward" : "back"} in browser history`,
                  tabId: updatedTab.id,
                  windowId: updatedTab.windowId,
                  url: updatedTab.url
                })
              }
            ],
            isError: false
          };
        } catch (error2) {
          if (chrome.runtime.lastError) {
            console.error(`Chrome API Error: ${chrome.runtime.lastError.message}`, error2);
            return createErrorResponse(`Chrome API Error: ${chrome.runtime.lastError.message}`);
          } else {
            console.error("Error in GoBackOrForwardTool.execute:", error2);
            return createErrorResponse(
              `Error navigating ${isForward ? "forward" : "back"}: ${error2 instanceof Error ? error2.message : String(error2)}`
            );
          }
        }
      });
    }
  }
  const goBackOrForwardTool = new GoBackOrForwardTool();
  class WindowTool extends BaseBrowserToolExecutor {
    constructor() {
      super(...arguments);
      __publicField2(this, "name", TOOL_NAMES.BROWSER.GET_WINDOWS_AND_TABS);
    }
    execute() {
      return __async(this, null, function* () {
        try {
          const windows = yield chrome.windows.getAll({ populate: true });
          let tabCount = 0;
          const structuredWindows = windows.map((window2) => {
            var _a3;
            const tabs = ((_a3 = window2.tabs) == null ? void 0 : _a3.map((tab) => {
              tabCount++;
              return {
                tabId: tab.id || 0,
                url: tab.url || "",
                title: tab.title || "",
                active: tab.active || false,
                lastAccessed: tab.lastAccessed || 0
              };
            })) || [];
            return {
              windowId: window2.id || 0,
              tabs
            };
          });
          const result2 = {
            windowCount: windows.length,
            tabCount,
            windows: structuredWindows
          };
          return {
            content: [
              {
                type: "text",
                text: JSON.stringify(result2)
              }
            ],
            isError: false
          };
        } catch (error2) {
          console.error("Error in WindowTool.execute:", error2);
          return createErrorResponse(
            `Error getting windows and tabs information: ${error2 instanceof Error ? error2.message : String(error2)}`
          );
        }
      });
    }
  }
  const windowTool = new WindowTool();
  const BACKGROUND_MESSAGE_TYPES$1 = {
    SWITCH_SEMANTIC_MODEL: "switch_semantic_model",
    GET_MODEL_STATUS: "get_model_status",
    UPDATE_MODEL_STATUS: "update_model_status",
    GET_STORAGE_STATS: "get_storage_stats",
    CLEAR_ALL_DATA: "clear_all_data",
    GET_SERVER_STATUS: "get_server_status",
    REFRESH_SERVER_STATUS: "refresh_server_status",
    SERVER_STATUS_CHANGED: "server_status_changed",
    INITIALIZE_SEMANTIC_ENGINE: "initialize_semantic_engine",
    GET_WEBSOCKET_LATENCY_METRICS: "get_websocket_latency_metrics",
    TRIGGER_WEBSOCKET_LATENCY_TEST: "trigger_websocket_latency_test",
    WEBSOCKET_LATENCY_UPDATED: "websocket_latency_updated",
    FETCH_IMAGE_URL: "fetch_image_url",
    // MCP 执行日志相关
    GET_MCP_LOG_STATS: "get_mcp_log_stats",
    QUERY_MCP_LOGS: "query_mcp_logs",
    CLEAR_MCP_LOGS: "clear_mcp_logs",
    CLEANUP_MCP_LOGS: "cleanup_mcp_logs",
    // 自动网络请求捕获相关
    START_AUTO_CAPTURE: "start_auto_capture",
    STOP_AUTO_CAPTURE: "stop_auto_capture",
    GET_CAPTURED_REQUESTS: "get_captured_requests",
    GET_SUCCESSFUL_REQUESTS: "get_successful_requests",
    GET_CAPTURE_STATS: "get_capture_stats",
    CLEAR_CAPTURED_REQUESTS: "clear_captured_requests",
    GET_AUTO_CAPTURE_STATUS: "get_auto_capture_status",
    PREVIEW_REQUEST: "preview_request"
    // 预览指定请求
  };
  const OFFSCREEN_MESSAGE_TYPES = {
    SIMILARITY_ENGINE_INIT: "similarityEngineInit",
    SIMILARITY_ENGINE_COMPUTE: "similarityEngineCompute",
    SIMILARITY_ENGINE_BATCH_COMPUTE: "similarityEngineBatchCompute",
    SIMILARITY_ENGINE_STATUS: "similarityEngineStatus"
  };
  const TOOL_MESSAGE_TYPES = {
    // Screenshot related
    SCREENSHOT_PREPARE_PAGE_FOR_CAPTURE: "preparePageForCapture",
    SCREENSHOT_GET_PAGE_DETAILS: "getPageDetails",
    SCREENSHOT_GET_ELEMENT_DETAILS: "getElementDetails",
    SCREENSHOT_SCROLL_PAGE: "scrollPage",
    SCREENSHOT_RESET_PAGE_AFTER_CAPTURE: "resetPageAfterCapture",
    // Web content fetching
    WEB_FETCHER_GET_HTML_CONTENT: "getHtmlContent",
    WEB_FETCHER_GET_TEXT_CONTENT: "getTextContent",
    // User interactions
    CLICK_ELEMENT: "clickElement",
    FILL_ELEMENT: "fillElement",
    SIMULATE_KEYBOARD: "simulateKeyboard",
    SCROLL_PAGE: "scrollPageElement",
    SCROLL_INTO_VIEW: "scrollIntoView",
    // Interactive elements
    GET_INTERACTIVE_ELEMENTS: "getInteractiveElements",
    // Network requests
    NETWORK_SEND_REQUEST: "sendPureNetworkRequest",
    // Semantic similarity engine
    SIMILARITY_ENGINE_INIT: "similarityEngineInit",
    SIMILARITY_ENGINE_COMPUTE_BATCH: "similarityEngineComputeBatch",
    // Element waiting
    WAIT_FOR_ELEMENT: "waitForElement"
  };
  const DEFAULT_NETWORK_REQUEST_TIMEOUT = 3e4;
  class NetworkRequestTool extends BaseBrowserToolExecutor {
    constructor() {
      super(...arguments);
      __publicField2(this, "name", TOOL_NAMES.BROWSER.NETWORK_REQUEST);
    }
    execute(args) {
      return __async(this, null, function* () {
        var _a3;
        const {
          url: url2,
          method = "GET",
          headers = {},
          body,
          timeout = DEFAULT_NETWORK_REQUEST_TIMEOUT
        } = args;
        console.log(`NetworkRequestTool: Executing with options:`, args);
        if (!url2) {
          return createErrorResponse("URL parameter is required.");
        }
        try {
          const tabs = yield chrome.tabs.query({ active: true, currentWindow: true });
          if (!((_a3 = tabs[0]) == null ? void 0 : _a3.id)) {
            return createErrorResponse("No active tab found or tab has no ID.");
          }
          const activeTabId = tabs[0].id;
          yield this.injectContentScript(activeTabId, ["inject-scripts/network-helper.js"]);
          console.log(
            `NetworkRequestTool: Sending to content script: URL=${url2}, Method=${method}, Headers=${Object.keys(headers).join(",")}, BodyType=${typeof body}`
          );
          const resultFromContentScript = yield this.sendMessageToTab(activeTabId, {
            action: TOOL_MESSAGE_TYPES.NETWORK_SEND_REQUEST,
            url: url2,
            method,
            headers,
            body,
            timeout
          });
          console.log(`NetworkRequestTool: Response from content script:`, resultFromContentScript);
          return {
            content: [
              {
                type: "text",
                text: JSON.stringify(resultFromContentScript)
              }
            ],
            isError: !(resultFromContentScript == null ? void 0 : resultFromContentScript.success)
          };
        } catch (error2) {
          console.error("NetworkRequestTool: Error sending network request:", error2);
          return createErrorResponse(
            `Error sending network request: ${error2.message || String(error2)}`
          );
        }
      });
    }
  }
  const networkRequestTool = new NetworkRequestTool();
  const STATIC_RESOURCE_EXTENSIONS$1 = [
    ".png",
    ".jpg",
    ".jpeg",
    ".gif",
    ".bmp",
    ".webp",
    ".svg",
    ".ico",
    ".cur",
    ".css",
    ".woff",
    ".woff2",
    ".ttf",
    ".eot",
    ".otf",
    ".mp3",
    ".mp4",
    ".avi",
    ".mov",
    ".webm",
    ".ogg",
    ".wav",
    ".pdf",
    ".zip",
    ".rar",
    ".7z",
    ".iso",
    ".dmg",
    ".js",
    ".jsx",
    ".ts",
    ".tsx",
    ".map"
    // Source maps
  ];
  const AD_ANALYTICS_DOMAINS$1 = [
    "google-analytics.com",
    "googletagmanager.com",
    "analytics.google.com",
    "doubleclick.net",
    "googlesyndication.com",
    "googleads.g.doubleclick.net",
    "facebook.com/tr",
    "connect.facebook.net",
    "bat.bing.com",
    "linkedin.com",
    // Often for tracking pixels/insights
    "analytics.twitter.com",
    "static.hotjar.com",
    "script.hotjar.com",
    "stats.g.doubleclick.net",
    "amazon-adsystem.com",
    "adservice.google.com",
    "pagead2.googlesyndication.com",
    "ads-twitter.com",
    "ads.yahoo.com",
    "adroll.com",
    "adnxs.com",
    "criteo.com",
    "quantserve.com",
    "scorecardresearch.com",
    "segment.io",
    "amplitude.com",
    "mixpanel.com",
    "optimizely.com",
    "crazyegg.com",
    "clicktale.net",
    "mouseflow.com",
    "fullstory.com",
    "clarity.ms"
  ];
  const DEBUGGER_PROTOCOL_VERSION$3 = "1.3";
  const MAX_RESPONSE_BODY_SIZE_BYTES = 10 * 1024 * 1024;
  const DEFAULT_MAX_CAPTURE_TIME_MS = 3 * 60 * 1e3;
  const DEFAULT_INACTIVITY_TIMEOUT_MS = 60 * 1e3;
  const _NetworkDebuggerStartTool = class _NetworkDebuggerStartTool extends BaseBrowserToolExecutor {
    constructor() {
      super();
      __publicField2(this, "name", TOOL_NAMES.BROWSER.NETWORK_DEBUGGER_START);
      __publicField2(this, "captureData", /* @__PURE__ */ new Map());
      // tabId -> capture data
      __publicField2(this, "captureTimers", /* @__PURE__ */ new Map());
      // tabId -> max capture timer
      __publicField2(this, "inactivityTimers", /* @__PURE__ */ new Map());
      // tabId -> inactivity timer
      __publicField2(this, "lastActivityTime", /* @__PURE__ */ new Map());
      // tabId -> timestamp of last network activity
      __publicField2(this, "pendingResponseBodies", /* @__PURE__ */ new Map());
      // requestId -> promise for getResponseBody
      __publicField2(this, "requestCounters", /* @__PURE__ */ new Map());
      if (_NetworkDebuggerStartTool.instance) {
        return _NetworkDebuggerStartTool.instance;
      }
      _NetworkDebuggerStartTool.instance = this;
      chrome.debugger.onEvent.addListener(this.handleDebuggerEvent.bind(this));
      chrome.debugger.onDetach.addListener(this.handleDebuggerDetach.bind(this));
      chrome.tabs.onRemoved.addListener(this.handleTabRemoved.bind(this));
      chrome.tabs.onCreated.addListener(this.handleTabCreated.bind(this));
    }
    handleTabRemoved(tabId) {
      if (this.captureData.has(tabId)) {
        console.log(`NetworkDebuggerStartTool: Tab ${tabId} was closed, cleaning up resources.`);
        this.cleanupCapture(tabId);
      }
    }
    /**
     * Handle tab creation events
     * If a new tab is opened from a tab that is currently capturing, automatically start capturing the new tab's requests
     */
    handleTabCreated(tab) {
      return __async(this, null, function* () {
        try {
          if (this.captureData.size === 0) return;
          const openerTabId = tab.openerTabId;
          if (!openerTabId) return;
          if (!this.captureData.has(openerTabId)) return;
          const newTabId = tab.id;
          if (!newTabId) return;
          console.log(
            `NetworkDebuggerStartTool: New tab ${newTabId} created from capturing tab ${openerTabId}, will extend capture to it.`
          );
          const openerCaptureInfo = this.captureData.get(openerTabId);
          if (!openerCaptureInfo) return;
          yield new Promise((resolve2) => setTimeout(resolve2, 500));
          yield this.startCaptureForTab(newTabId, {
            maxCaptureTime: openerCaptureInfo.maxCaptureTime,
            inactivityTimeout: openerCaptureInfo.inactivityTimeout,
            includeStatic: openerCaptureInfo.includeStatic
          });
          console.log(`NetworkDebuggerStartTool: Successfully extended capture to new tab ${newTabId}`);
        } catch (error2) {
          console.error(`NetworkDebuggerStartTool: Error extending capture to new tab:`, error2);
        }
      });
    }
    /**
     * Start network request capture for specified tab
     * @param tabId Tab ID
     * @param options Capture options
     */
    startCaptureForTab(tabId, options) {
      return __async(this, null, function* () {
        var _a3;
        const { maxCaptureTime, inactivityTimeout, includeStatic } = options;
        if (this.captureData.has(tabId)) {
          console.log(
            `NetworkDebuggerStartTool: Already capturing on tab ${tabId}. Stopping previous session.`
          );
          yield this.stopCapture(tabId);
        }
        try {
          const tab = yield chrome.tabs.get(tabId);
          const targets = yield chrome.debugger.getTargets();
          const existingTarget = targets.find(
            (t) => t.tabId === tabId && t.attached && t.type === "page"
          );
          if (existingTarget && !existingTarget.extensionId) {
            throw new Error(
              `Debugger is already attached to tab ${tabId} by another tool (e.g., DevTools).`
            );
          }
          try {
            yield chrome.debugger.attach({ tabId }, DEBUGGER_PROTOCOL_VERSION$3);
          } catch (error2) {
            if ((_a3 = error2.message) == null ? void 0 : _a3.includes("Cannot attach to the target with an attached client")) {
              throw new Error(
                `Debugger is already attached to tab ${tabId}. This might be DevTools or another extension.`
              );
            }
            throw error2;
          }
          try {
            yield chrome.debugger.sendCommand({ tabId }, "Network.enable");
          } catch (error2) {
            yield chrome.debugger.detach({ tabId }).catch((e) => console.warn("Error detaching after failed enable:", e));
            throw error2;
          }
          this.captureData.set(tabId, {
            startTime: Date.now(),
            tabUrl: tab.url,
            tabTitle: tab.title,
            maxCaptureTime,
            inactivityTimeout,
            includeStatic,
            requests: {},
            limitReached: false
          });
          this.requestCounters.set(tabId, 0);
          this.updateLastActivityTime(tabId);
          console.log(
            `NetworkDebuggerStartTool: Started capture for tab ${tabId} (${tab.url}). Max requests: ${_NetworkDebuggerStartTool.MAX_REQUESTS_PER_CAPTURE}, Max time: ${maxCaptureTime}ms, Inactivity: ${inactivityTimeout}ms.`
          );
          if (maxCaptureTime > 0) {
            this.captureTimers.set(
              tabId,
              setTimeout(() => __async(this, null, function* () {
                console.log(
                  `NetworkDebuggerStartTool: Max capture time (${maxCaptureTime}ms) reached for tab ${tabId}.`
                );
                yield this.stopCapture(tabId, true);
              }), maxCaptureTime)
            );
          }
        } catch (error2) {
          console.error(`NetworkDebuggerStartTool: Error starting capture for tab ${tabId}:`, error2);
          if (this.captureData.has(tabId)) {
            yield chrome.debugger.detach({ tabId }).catch((e) => console.warn("Cleanup detach error:", e));
            this.cleanupCapture(tabId);
          }
          throw error2;
        }
      });
    }
    handleDebuggerEvent(source, method, params) {
      if (!source.tabId) return;
      const tabId = source.tabId;
      const captureInfo = this.captureData.get(tabId);
      if (!captureInfo) return;
      this.updateLastActivityTime(tabId);
      switch (method) {
        case "Network.requestWillBeSent":
          this.handleRequestWillBeSent(tabId, params);
          break;
        case "Network.responseReceived":
          this.handleResponseReceived(tabId, params);
          break;
        case "Network.loadingFinished":
          this.handleLoadingFinished(tabId, params);
          break;
        case "Network.loadingFailed":
          this.handleLoadingFailed(tabId, params);
          break;
      }
    }
    handleDebuggerDetach(source, reason) {
      if (source.tabId && this.captureData.has(source.tabId)) {
        console.log(
          `NetworkDebuggerStartTool: Debugger detached from tab ${source.tabId}, reason: ${reason}. Cleaning up.`
        );
        this.cleanupCapture(source.tabId);
      }
    }
    updateLastActivityTime(tabId) {
      this.lastActivityTime.set(tabId, Date.now());
      const captureInfo = this.captureData.get(tabId);
      if (captureInfo && captureInfo.inactivityTimeout > 0) {
        if (this.inactivityTimers.has(tabId)) {
          clearTimeout(this.inactivityTimers.get(tabId));
        }
        this.inactivityTimers.set(
          tabId,
          setTimeout(() => this.checkInactivity(tabId), captureInfo.inactivityTimeout)
        );
      }
    }
    checkInactivity(tabId) {
      const captureInfo = this.captureData.get(tabId);
      if (!captureInfo) return;
      const lastActivity = this.lastActivityTime.get(tabId) || captureInfo.startTime;
      const now = Date.now();
      const inactiveTime = now - lastActivity;
      if (inactiveTime >= captureInfo.inactivityTimeout) {
        console.log(
          `NetworkDebuggerStartTool: No activity for ${inactiveTime}ms (threshold: ${captureInfo.inactivityTimeout}ms), stopping capture for tab ${tabId}`
        );
        this.stopCaptureByInactivity(tabId);
      } else {
        const remainingTime = Math.max(0, captureInfo.inactivityTimeout - inactiveTime);
        this.inactivityTimers.set(
          tabId,
          setTimeout(() => this.checkInactivity(tabId), remainingTime)
        );
      }
    }
    stopCaptureByInactivity(tabId) {
      return __async(this, null, function* () {
        const captureInfo = this.captureData.get(tabId);
        if (!captureInfo) return;
        console.log(`NetworkDebuggerStartTool: Stopping capture due to inactivity for tab ${tabId}.`);
        yield this.stopCapture(tabId, true);
      });
    }
    shouldFilterRequestByUrl(url2) {
      try {
        const urlObj = new URL(url2);
        if (AD_ANALYTICS_DOMAINS$1.some((domain2) => urlObj.hostname.includes(domain2))) {
          return true;
        }
        return false;
      } catch (e) {
        console.error(`NetworkDebuggerStartTool: Error parsing URL for filtering: ${url2}`, e);
        return false;
      }
    }
    shouldFilterRequestByExtension(url2, includeStatic) {
      if (includeStatic) return false;
      try {
        const urlObj = new URL(url2);
        const path = urlObj.pathname.toLowerCase();
        if (STATIC_RESOURCE_EXTENSIONS$1.some((ext) => path.endsWith(ext))) {
          return true;
        }
        return false;
      } catch (e) {
        console.error(
          `NetworkDebuggerStartTool: Error parsing URL for extension filtering: ${url2}`,
          e
        );
        return false;
      }
    }
    // MIME type-based filtering, called after response is received
    shouldFilterByMimeType(mimeType, includeStatic) {
      if (!mimeType) return false;
      if (_NetworkDebuggerStartTool.API_MIME_TYPES.some((apiMime) => mimeType.startsWith(apiMime))) {
        return false;
      }
      if (!includeStatic) {
        if (_NetworkDebuggerStartTool.STATIC_MIME_TYPES_TO_FILTER.some(
          (staticMime) => mimeType.startsWith(staticMime)
        )) {
          return true;
        }
      }
      return false;
    }
    handleRequestWillBeSent(tabId, params) {
      const captureInfo = this.captureData.get(tabId);
      if (!captureInfo) return;
      const { requestId, request, timestamp, type: type2, loaderId, frameId } = params;
      if (this.shouldFilterRequestByUrl(request.url) || this.shouldFilterRequestByExtension(request.url, captureInfo.includeStatic)) {
        return;
      }
      const currentCount = this.requestCounters.get(tabId) || 0;
      if (currentCount >= _NetworkDebuggerStartTool.MAX_REQUESTS_PER_CAPTURE) {
        captureInfo.limitReached = true;
        return;
      }
      if (!captureInfo.requests[requestId]) {
        captureInfo.requests[requestId] = {
          requestId,
          url: request.url,
          method: request.method,
          requestHeaders: request.headers,
          // Temporary, will be processed
          requestTime: timestamp * 1e3,
          // Convert seconds to milliseconds
          type: type2 || "Other",
          status: "pending",
          // Initial status
          loaderId,
          // Useful for tracking redirects
          frameId
          // Useful for context
        };
        if (request.postData) {
          captureInfo.requests[requestId].requestBody = request.postData;
        }
      } else {
        const existingRequest = captureInfo.requests[requestId];
        existingRequest.url = request.url;
        existingRequest.requestTime = timestamp * 1e3;
        if (request.headers) existingRequest.requestHeaders = request.headers;
        if (request.postData) existingRequest.requestBody = request.postData;
        else delete existingRequest.requestBody;
      }
    }
    handleResponseReceived(tabId, params) {
      const captureInfo = this.captureData.get(tabId);
      if (!captureInfo) return;
      const { requestId, response, timestamp, type: type2 } = params;
      const requestInfo = captureInfo.requests[requestId];
      if (!requestInfo) {
        return;
      }
      if (this.shouldFilterByMimeType(response.mimeType, captureInfo.includeStatic)) {
        delete captureInfo.requests[requestId];
        return;
      }
      const currentStoredCount = Object.keys(captureInfo.requests).length;
      this.requestCounters.set(tabId, currentStoredCount);
      requestInfo.status = response.status === 0 ? "pending" : "complete";
      requestInfo.statusCode = response.status;
      requestInfo.statusText = response.statusText;
      requestInfo.responseHeaders = response.headers;
      requestInfo.mimeType = response.mimeType;
      requestInfo.responseTime = timestamp * 1e3;
      if (type2) requestInfo.type = type2;
    }
    handleLoadingFinished(tabId, params) {
      return __async(this, null, function* () {
        const captureInfo = this.captureData.get(tabId);
        if (!captureInfo) return;
        const { requestId, encodedDataLength } = params;
        const requestInfo = captureInfo.requests[requestId];
        if (!requestInfo) {
          return;
        }
        requestInfo.encodedDataLength = encodedDataLength;
        if (requestInfo.status === "pending") requestInfo.status = "complete";
        if (this.shouldCaptureResponseBody(requestInfo)) {
          try {
            const responseBodyData = yield this.getResponseBody(tabId, requestId);
            if (responseBodyData) {
              let bodyText;
              if (responseBodyData.body && responseBodyData.body.length > MAX_RESPONSE_BODY_SIZE_BYTES) {
                bodyText = responseBodyData.body.substring(0, MAX_RESPONSE_BODY_SIZE_BYTES) + `

... [Response truncated, total size: ${responseBodyData.body.length} bytes] ...`;
              } else {
                bodyText = responseBodyData.body;
              }
              requestInfo.base64Encoded = responseBodyData.base64Encoded;
              if (!responseBodyData.base64Encoded && bodyText) {
                try {
                  requestInfo.responseBody = JSON.parse(bodyText);
                } catch (e) {
                  requestInfo.responseBody = bodyText;
                }
              } else {
                requestInfo.responseBody = bodyText;
              }
            }
          } catch (error2) {
            requestInfo.errorText = (requestInfo.errorText || "") + ` Failed to get body: ${error2 instanceof Error ? error2.message : String(error2)}`;
          }
        }
      });
    }
    shouldCaptureResponseBody(requestInfo) {
      const mimeType = requestInfo.mimeType || "";
      if (_NetworkDebuggerStartTool.API_MIME_TYPES.some((type2) => mimeType.startsWith(type2))) {
        return true;
      }
      const url2 = requestInfo.url.toLowerCase();
      if (/\/(api|service|rest|graphql|query|data|rpc|v[0-9]+)\//i.test(url2) || url2.includes(".json") || url2.includes("json=") || url2.includes("format=json")) {
        if (mimeType && _NetworkDebuggerStartTool.STATIC_MIME_TYPES_TO_FILTER.some(
          (staticMime) => mimeType.startsWith(staticMime)
        )) {
          return false;
        }
        return true;
      }
      return false;
    }
    handleLoadingFailed(tabId, params) {
      const captureInfo = this.captureData.get(tabId);
      if (!captureInfo) return;
      const { requestId, errorText, canceled, type: type2 } = params;
      const requestInfo = captureInfo.requests[requestId];
      if (!requestInfo) {
        return;
      }
      requestInfo.status = "error";
      requestInfo.errorText = errorText;
      requestInfo.canceled = canceled;
      if (type2) requestInfo.type = type2;
    }
    getResponseBody(tabId, requestId) {
      return __async(this, null, function* () {
        const pendingKey = `${tabId}_${requestId}`;
        if (this.pendingResponseBodies.has(pendingKey)) {
          return this.pendingResponseBodies.get(pendingKey);
        }
        const responseBodyPromise = (() => __async(this, null, function* () {
          try {
            const attachedTabs = yield chrome.debugger.getTargets();
            if (!attachedTabs.some((target) => target.tabId === tabId && target.attached)) {
              throw new Error(`Debugger not attached to tab ${tabId}`);
            }
            const result2 = yield chrome.debugger.sendCommand({ tabId }, "Network.getResponseBody", {
              requestId
            });
            return result2;
          } finally {
            this.pendingResponseBodies.delete(pendingKey);
          }
        }))();
        this.pendingResponseBodies.set(pendingKey, responseBodyPromise);
        return responseBodyPromise;
      });
    }
    cleanupCapture(tabId) {
      if (this.captureTimers.has(tabId)) {
        clearTimeout(this.captureTimers.get(tabId));
        this.captureTimers.delete(tabId);
      }
      if (this.inactivityTimers.has(tabId)) {
        clearTimeout(this.inactivityTimers.get(tabId));
        this.inactivityTimers.delete(tabId);
      }
      this.lastActivityTime.delete(tabId);
      this.captureData.delete(tabId);
      this.requestCounters.delete(tabId);
      const keysToDelete = [];
      this.pendingResponseBodies.forEach((_, key) => {
        if (key.startsWith(`${tabId}_`)) {
          keysToDelete.push(key);
        }
      });
      keysToDelete.forEach((key) => this.pendingResponseBodies.delete(key));
      console.log(`NetworkDebuggerStartTool: Cleaned up resources for tab ${tabId}.`);
    }
    // isAutoStop is true if stop was triggered by timeout, false if by user/explicit call
    stopCapture(tabId, isAutoStop = false) {
      return __async(this, null, function* () {
        const captureInfo = this.captureData.get(tabId);
        if (!captureInfo) {
          return { success: false, message: "No capture in progress for this tab." };
        }
        console.log(
          `NetworkDebuggerStartTool: Stopping capture for tab ${tabId}. Auto-stop: ${isAutoStop}`
        );
        try {
          const attachedTargets = yield chrome.debugger.getTargets();
          const isAttached = attachedTargets.some(
            (target) => target.tabId === tabId && target.attached
          );
          if (isAttached) {
            try {
              yield chrome.debugger.sendCommand({ tabId }, "Network.disable");
            } catch (e) {
              console.warn(
                `NetworkDebuggerStartTool: Error disabling network for tab ${tabId} (possibly already detached):`,
                e
              );
            }
            try {
              yield chrome.debugger.detach({ tabId });
            } catch (e) {
              console.warn(
                `NetworkDebuggerStartTool: Error detaching debugger for tab ${tabId} (possibly already detached):`,
                e
              );
            }
          } else {
            console.log(
              `NetworkDebuggerStartTool: Debugger was not attached to tab ${tabId} at stopCapture.`
            );
          }
        } catch (error2) {
          console.error(
            "NetworkDebuggerStartTool: Error during debugger interaction in stopCapture:",
            error2
          );
        }
        const allRequests = Object.values(captureInfo.requests);
        const commonRequestHeaders = this.analyzeCommonHeaders(allRequests, "requestHeaders");
        const commonResponseHeaders = this.analyzeCommonHeaders(allRequests, "responseHeaders");
        const processedRequests = allRequests.map((req) => {
          const finalReq = __spreadValues({}, req);
          if (finalReq.requestHeaders) {
            finalReq.specificRequestHeaders = this.filterOutCommonHeaders(
              finalReq.requestHeaders,
              commonRequestHeaders
            );
            delete finalReq.requestHeaders;
          } else {
            finalReq.specificRequestHeaders = {};
          }
          if (finalReq.responseHeaders) {
            finalReq.specificResponseHeaders = this.filterOutCommonHeaders(
              finalReq.responseHeaders,
              commonResponseHeaders
            );
            delete finalReq.responseHeaders;
          } else {
            finalReq.specificResponseHeaders = {};
          }
          return finalReq;
        });
        processedRequests.sort((a, b) => (a.requestTime || 0) - (b.requestTime || 0));
        const resultData = {
          captureStartTime: captureInfo.startTime,
          captureEndTime: Date.now(),
          totalDurationMs: Date.now() - captureInfo.startTime,
          commonRequestHeaders,
          commonResponseHeaders,
          requests: processedRequests,
          requestCount: processedRequests.length,
          // Actual stored requests
          totalRequestsReceivedBeforeLimit: captureInfo.limitReached ? _NetworkDebuggerStartTool.MAX_REQUESTS_PER_CAPTURE : processedRequests.length,
          requestLimitReached: !!captureInfo.limitReached,
          stoppedBy: isAutoStop ? this.lastActivityTime.get(tabId) ? "inactivity_timeout" : "max_capture_time" : "user_request",
          tabUrl: captureInfo.tabUrl,
          tabTitle: captureInfo.tabTitle
        };
        console.log(
          `NetworkDebuggerStartTool: Capture stopped for tab ${tabId}. ${resultData.requestCount} requests processed. Limit reached: ${resultData.requestLimitReached}. Stopped by: ${resultData.stoppedBy}`
        );
        this.cleanupCapture(tabId);
        return {
          success: true,
          message: `Capture stopped. ${resultData.requestCount} requests.`,
          data: resultData
        };
      });
    }
    analyzeCommonHeaders(requests, headerTypeKey) {
      if (!requests || requests.length === 0) return {};
      const headerValueCounts = /* @__PURE__ */ new Map();
      let requestsWithHeadersCount = 0;
      for (const req of requests) {
        const headers = req[headerTypeKey];
        if (headers && Object.keys(headers).length > 0) {
          requestsWithHeadersCount++;
          for (const name2 in headers) {
            const lowerName = name2.toLowerCase();
            const value = headers[name2];
            if (!headerValueCounts.has(lowerName)) {
              headerValueCounts.set(lowerName, /* @__PURE__ */ new Map());
            }
            const values = headerValueCounts.get(lowerName);
            values.set(value, (values.get(value) || 0) + 1);
          }
        }
      }
      if (requestsWithHeadersCount === 0) return {};
      const commonHeaders = {};
      headerValueCounts.forEach((values, name2) => {
        values.forEach((count, value) => {
          if (count === requestsWithHeadersCount) {
            let originalName = name2;
            for (const req of requests) {
              const hdrs = req[headerTypeKey];
              if (hdrs) {
                const foundName = Object.keys(hdrs).find((k) => k.toLowerCase() === name2);
                if (foundName) {
                  originalName = foundName;
                  break;
                }
              }
            }
            commonHeaders[originalName] = value;
          }
        });
      });
      return commonHeaders;
    }
    filterOutCommonHeaders(headers, commonHeaders) {
      if (!headers || typeof headers !== "object") return {};
      const specificHeaders = {};
      const commonHeadersLower = {};
      Object.keys(commonHeaders).forEach((commonName) => {
        commonHeadersLower[commonName.toLowerCase()] = commonHeaders[commonName];
      });
      Object.keys(headers).forEach((name2) => {
        const lowerName = name2.toLowerCase();
        if (!(lowerName in commonHeadersLower) || headers[name2] !== commonHeadersLower[lowerName]) {
          specificHeaders[name2] = headers[name2];
        }
      });
      return specificHeaders;
    }
    execute(args) {
      return __async(this, null, function* () {
        var _a3, _b2;
        const {
          url: targetUrl,
          maxCaptureTime = DEFAULT_MAX_CAPTURE_TIME_MS,
          inactivityTimeout = DEFAULT_INACTIVITY_TIMEOUT_MS,
          includeStatic = false
        } = args;
        console.log(
          `NetworkDebuggerStartTool: Executing with args: url=${targetUrl}, maxTime=${maxCaptureTime}, inactivityTime=${inactivityTimeout}, includeStatic=${includeStatic}`
        );
        let tabToOperateOn;
        try {
          if (targetUrl) {
            const existingTabs = yield chrome.tabs.query({
              url: targetUrl.startsWith("http") ? targetUrl : `*://*/*${targetUrl}*`
            });
            if (existingTabs.length > 0 && ((_a3 = existingTabs[0]) == null ? void 0 : _a3.id)) {
              tabToOperateOn = existingTabs[0];
              yield chrome.windows.update(tabToOperateOn.windowId, { focused: true });
              yield chrome.tabs.update(tabToOperateOn.id, { active: true });
            } else {
              tabToOperateOn = yield chrome.tabs.create({ url: targetUrl, active: true });
              yield new Promise((resolve2) => setTimeout(resolve2, 500));
            }
          } else {
            const activeTabs = yield chrome.tabs.query({ active: true, currentWindow: true });
            if (activeTabs.length > 0 && ((_b2 = activeTabs[0]) == null ? void 0 : _b2.id)) {
              tabToOperateOn = activeTabs[0];
            } else {
              return createErrorResponse("No active tab found and no URL provided.");
            }
          }
          if (!(tabToOperateOn == null ? void 0 : tabToOperateOn.id)) {
            return createErrorResponse("Failed to identify or create a target tab.");
          }
          const tabId = tabToOperateOn.id;
          try {
            yield this.startCaptureForTab(tabId, {
              maxCaptureTime,
              inactivityTimeout,
              includeStatic
            });
          } catch (error2) {
            return createErrorResponse(
              `Failed to start capture for tab ${tabId}: ${error2.message || String(error2)}`
            );
          }
          return {
            content: [
              {
                type: "text",
                text: JSON.stringify({
                  success: true,
                  message: `Network capture started on tab ${tabId}. Waiting for stop command or timeout.`,
                  tabId,
                  url: tabToOperateOn.url,
                  maxCaptureTime,
                  inactivityTimeout,
                  includeStatic,
                  maxRequests: _NetworkDebuggerStartTool.MAX_REQUESTS_PER_CAPTURE
                })
              }
            ],
            isError: false
          };
        } catch (error2) {
          console.error("NetworkDebuggerStartTool: Critical error during execute:", error2);
          const tabIdToClean = tabToOperateOn == null ? void 0 : tabToOperateOn.id;
          if (tabIdToClean && this.captureData.has(tabIdToClean)) {
            yield chrome.debugger.detach({ tabId: tabIdToClean }).catch((e) => console.warn("Cleanup detach error:", e));
            this.cleanupCapture(tabIdToClean);
          }
          return createErrorResponse(
            `Error in NetworkDebuggerStartTool: ${error2.message || String(error2)}`
          );
        }
      });
    }
  };
  // tabId -> count of captured requests (after filtering)
  __publicField2(_NetworkDebuggerStartTool, "MAX_REQUESTS_PER_CAPTURE", 100);
  // Max requests to store to prevent memory issues
  __publicField2(_NetworkDebuggerStartTool, "instance", null);
  // Static resource MIME types list (used when includeStatic is false)
  __publicField2(_NetworkDebuggerStartTool, "STATIC_MIME_TYPES_TO_FILTER", [
    "image/",
    // all image types (image/png, image/jpeg, etc.)
    "font/",
    // all font types (font/woff, font/ttf, etc.)
    "audio/",
    // all audio types
    "video/",
    // all video types
    "text/css",
    // Note: text/javascript, application/javascript etc. are often filtered by extension.
    // If script files need to be filtered by MIME type as well, add them here.
    // 'application/javascript',
    // 'application/x-javascript',
    "application/pdf",
    "application/zip",
    "application/octet-stream"
    // Often used for downloads or generic binary data
  ]);
  // API-like response MIME types (these are generally NOT filtered, and we might want their bodies)
  __publicField2(_NetworkDebuggerStartTool, "API_MIME_TYPES", [
    "application/json",
    "application/xml",
    "text/xml",
    // 'text/json' is not standard, but sometimes seen. 'application/json' is preferred.
    "text/plain",
    // Can be API response, handle with care. Often captured.
    "application/x-www-form-urlencoded",
    // Form submissions, can be API calls
    "application/graphql"
    // Add other common API types if needed
  ]);
  let NetworkDebuggerStartTool = _NetworkDebuggerStartTool;
  const _NetworkDebuggerStopTool = class _NetworkDebuggerStopTool extends BaseBrowserToolExecutor {
    constructor() {
      super();
      __publicField2(this, "name", TOOL_NAMES.BROWSER.NETWORK_DEBUGGER_STOP);
      if (_NetworkDebuggerStopTool.instance) {
        return _NetworkDebuggerStopTool.instance;
      }
      _NetworkDebuggerStopTool.instance = this;
    }
    execute() {
      return __async(this, null, function* () {
        var _a3;
        console.log(`NetworkDebuggerStopTool: Executing command.`);
        const startTool = NetworkDebuggerStartTool.instance;
        if (!startTool) {
          return createErrorResponse(
            "NetworkDebuggerStartTool instance not available. Cannot stop capture."
          );
        }
        const ongoingCaptures = Array.from(startTool["captureData"].keys());
        console.log(
          `NetworkDebuggerStopTool: Found ${ongoingCaptures.length} ongoing captures: ${ongoingCaptures.join(", ")}`
        );
        if (ongoingCaptures.length === 0) {
          return createErrorResponse("No active network captures found in any tab.");
        }
        const activeTabs = yield chrome.tabs.query({ active: true, currentWindow: true });
        const activeTabId = (_a3 = activeTabs[0]) == null ? void 0 : _a3.id;
        let primaryTabId;
        if (activeTabId && startTool["captureData"].has(activeTabId)) {
          primaryTabId = activeTabId;
          console.log(
            `NetworkDebuggerStopTool: Active tab ${activeTabId} is capturing, will stop it first.`
          );
        } else if (ongoingCaptures.length === 1) {
          primaryTabId = ongoingCaptures[0];
          console.log(
            `NetworkDebuggerStopTool: Only one tab ${primaryTabId} is capturing, stopping it.`
          );
        } else {
          primaryTabId = ongoingCaptures[0];
          console.log(
            `NetworkDebuggerStopTool: Multiple tabs capturing, active tab not among them. Stopping tab ${primaryTabId} first.`
          );
        }
        const result2 = yield this.performStop(startTool, primaryTabId);
        if (ongoingCaptures.length > 1) {
          const otherTabIds = ongoingCaptures.filter((id2) => id2 !== primaryTabId);
          console.log(
            `NetworkDebuggerStopTool: Stopping ${otherTabIds.length} additional captures: ${otherTabIds.join(", ")}`
          );
          for (const tabId of otherTabIds) {
            try {
              yield startTool.stopCapture(tabId);
            } catch (error2) {
              console.error(`NetworkDebuggerStopTool: Error stopping capture on tab ${tabId}:`, error2);
            }
          }
        }
        return result2;
      });
    }
    performStop(startTool, tabId) {
      return __async(this, null, function* () {
        console.log(`NetworkDebuggerStopTool: Attempting to stop capture for tab ${tabId}.`);
        const stopResult = yield startTool.stopCapture(tabId);
        if (!(stopResult == null ? void 0 : stopResult.success)) {
          return createErrorResponse(
            (stopResult == null ? void 0 : stopResult.message) || `Failed to stop network capture for tab ${tabId}. It might not have been capturing.`
          );
        }
        const resultData = stopResult.data || {};
        const remainingCaptures = Array.from(startTool["captureData"].keys());
        if (resultData.requests && Array.isArray(resultData.requests)) {
          resultData.requests.sort(
            (a, b) => (a.requestTime || 0) - (b.requestTime || 0)
          );
        }
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify({
                success: true,
                message: `Capture for tab ${tabId} (${resultData.tabUrl || "N/A"}) stopped. ${resultData.requestCount || 0} requests captured.`,
                tabId,
                tabUrl: resultData.tabUrl || "N/A",
                tabTitle: resultData.tabTitle || "Unknown Tab",
                requestCount: resultData.requestCount || 0,
                commonRequestHeaders: resultData.commonRequestHeaders || {},
                commonResponseHeaders: resultData.commonResponseHeaders || {},
                requests: resultData.requests || [],
                captureStartTime: resultData.captureStartTime,
                captureEndTime: resultData.captureEndTime,
                totalDurationMs: resultData.totalDurationMs,
                settingsUsed: resultData.settingsUsed || {},
                remainingCaptures,
                totalRequestsReceived: resultData.totalRequestsReceived || resultData.requestCount || 0,
                requestLimitReached: resultData.requestLimitReached || false
              })
            }
          ],
          isError: false
        };
      });
    }
  };
  __publicField2(_NetworkDebuggerStopTool, "instance", null);
  let NetworkDebuggerStopTool = _NetworkDebuggerStopTool;
  const networkDebuggerStartTool = new NetworkDebuggerStartTool();
  const networkDebuggerStopTool = new NetworkDebuggerStopTool();
  const STATIC_RESOURCE_EXTENSIONS = [
    ".jpg",
    ".jpeg",
    ".png",
    ".gif",
    ".svg",
    ".webp",
    ".ico",
    ".bmp",
    // Images
    ".css",
    ".scss",
    ".less",
    // Styles
    ".js",
    ".jsx",
    ".ts",
    ".tsx",
    // Scripts
    ".woff",
    ".woff2",
    ".ttf",
    ".eot",
    ".otf",
    // Fonts
    ".mp3",
    ".mp4",
    ".avi",
    ".mov",
    ".wmv",
    ".flv",
    ".ogg",
    ".wav",
    // Media
    ".pdf",
    ".doc",
    ".docx",
    ".xls",
    ".xlsx",
    ".ppt",
    ".pptx"
    // Documents
  ];
  const AD_ANALYTICS_DOMAINS = NETWORK_FILTERS.EXCLUDED_DOMAINS;
  const _NetworkCaptureStartTool = class _NetworkCaptureStartTool extends BaseBrowserToolExecutor {
    constructor() {
      super();
      __publicField2(this, "name", TOOL_NAMES.BROWSER.NETWORK_CAPTURE_START);
      __publicField2(this, "captureData", /* @__PURE__ */ new Map());
      // tabId -> capture data
      __publicField2(this, "captureTimers", /* @__PURE__ */ new Map());
      // tabId -> max capture timer
      __publicField2(this, "inactivityTimers", /* @__PURE__ */ new Map());
      // tabId -> inactivity timer
      __publicField2(this, "lastActivityTime", /* @__PURE__ */ new Map());
      // tabId -> timestamp of last activity
      __publicField2(this, "requestCounters", /* @__PURE__ */ new Map());
      // Maximum capture request count
      __publicField2(this, "listeners", {});
      if (_NetworkCaptureStartTool.instance) {
        return _NetworkCaptureStartTool.instance;
      }
      _NetworkCaptureStartTool.instance = this;
      chrome.tabs.onRemoved.addListener(this.handleTabRemoved.bind(this));
      chrome.tabs.onCreated.addListener(this.handleTabCreated.bind(this));
    }
    /**
     * Handle tab close events
     */
    handleTabRemoved(tabId) {
      if (this.captureData.has(tabId)) {
        console.log(`NetworkCaptureV2: Tab ${tabId} was closed, cleaning up resources.`);
        this.cleanupCapture(tabId);
      }
    }
    /**
     * Handle tab creation events
     * If a new tab is opened from a tab being captured, automatically start capturing the new tab's requests
     */
    handleTabCreated(tab) {
      return __async(this, null, function* () {
        try {
          if (this.captureData.size === 0) return;
          const openerTabId = tab.openerTabId;
          if (!openerTabId) return;
          if (!this.captureData.has(openerTabId)) return;
          const newTabId = tab.id;
          if (!newTabId) return;
          console.log(
            `NetworkCaptureV2: New tab ${newTabId} created from capturing tab ${openerTabId}, will extend capture to it.`
          );
          const openerCaptureInfo = this.captureData.get(openerTabId);
          if (!openerCaptureInfo) return;
          yield new Promise((resolve2) => setTimeout(resolve2, 500));
          yield this.startCaptureForTab(newTabId, {
            maxCaptureTime: openerCaptureInfo.maxCaptureTime,
            inactivityTimeout: openerCaptureInfo.inactivityTimeout,
            includeStatic: openerCaptureInfo.includeStatic
          });
          console.log(`NetworkCaptureV2: Successfully extended capture to new tab ${newTabId}`);
        } catch (error2) {
          console.error(`NetworkCaptureV2: Error extending capture to new tab:`, error2);
        }
      });
    }
    /**
     * Determine whether a request should be filtered (based on URL)
     */
    shouldFilterRequest(url2, includeStatic) {
      try {
        const urlObj = new URL(url2);
        if (AD_ANALYTICS_DOMAINS.some((domain2) => urlObj.hostname.includes(domain2))) {
          console.log(`NetworkCaptureV2: Filtering ad/analytics domain: ${urlObj.hostname}`);
          return true;
        }
        if (!includeStatic) {
          const path = urlObj.pathname.toLowerCase();
          if (STATIC_RESOURCE_EXTENSIONS.some((ext) => path.endsWith(ext))) {
            console.log(`NetworkCaptureV2: Filtering static resource by extension: ${path}`);
            return true;
          }
        }
        return false;
      } catch (e) {
        console.error("NetworkCaptureV2: Error filtering URL:", e);
        return false;
      }
    }
    /**
     * Filter based on MIME type
     */
    shouldFilterByMimeType(mimeType, includeStatic) {
      if (!mimeType) return false;
      if (_NetworkCaptureStartTool.API_MIME_TYPES.some((type2) => mimeType.startsWith(type2))) {
        return false;
      }
      if (!includeStatic) {
        if (_NetworkCaptureStartTool.STATIC_MIME_TYPES_TO_FILTER.some(
          (type2) => mimeType.startsWith(type2)
        )) {
          console.log(`NetworkCaptureV2: Filtering static resource by MIME type: ${mimeType}`);
          return true;
        }
        if (mimeType.startsWith("text/")) {
          console.log(`NetworkCaptureV2: Filtering text response: ${mimeType}`);
          return true;
        }
      }
      return false;
    }
    /**
     * Update last activity time and reset inactivity timer
     */
    updateLastActivityTime(tabId) {
      const captureInfo = this.captureData.get(tabId);
      if (!captureInfo) return;
      this.lastActivityTime.set(tabId, Date.now());
      if (this.inactivityTimers.has(tabId)) {
        clearTimeout(this.inactivityTimers.get(tabId));
      }
      if (captureInfo.inactivityTimeout > 0) {
        this.inactivityTimers.set(
          tabId,
          setTimeout(() => this.checkInactivity(tabId), captureInfo.inactivityTimeout)
        );
      }
    }
    /**
     * Check for inactivity
     */
    checkInactivity(tabId) {
      const captureInfo = this.captureData.get(tabId);
      if (!captureInfo) return;
      const lastActivity = this.lastActivityTime.get(tabId) || captureInfo.startTime;
      const now = Date.now();
      const inactiveTime = now - lastActivity;
      if (inactiveTime >= captureInfo.inactivityTimeout) {
        console.log(
          `NetworkCaptureV2: No activity for ${inactiveTime}ms, stopping capture for tab ${tabId}`
        );
        this.stopCaptureByInactivity(tabId);
      } else {
        const remainingTime = captureInfo.inactivityTimeout - inactiveTime;
        this.inactivityTimers.set(
          tabId,
          setTimeout(() => this.checkInactivity(tabId), remainingTime)
        );
      }
    }
    /**
     * Stop capture due to inactivity
     */
    stopCaptureByInactivity(tabId) {
      return __async(this, null, function* () {
        const captureInfo = this.captureData.get(tabId);
        if (!captureInfo) return;
        console.log(`NetworkCaptureV2: Stopping capture due to inactivity for tab ${tabId}`);
        yield this.stopCapture(tabId);
      });
    }
    /**
     * Clean up capture resources
     */
    cleanupCapture(tabId) {
      if (this.captureTimers.has(tabId)) {
        clearTimeout(this.captureTimers.get(tabId));
        this.captureTimers.delete(tabId);
      }
      if (this.inactivityTimers.has(tabId)) {
        clearTimeout(this.inactivityTimers.get(tabId));
        this.inactivityTimers.delete(tabId);
      }
      this.lastActivityTime.delete(tabId);
      this.captureData.delete(tabId);
      this.requestCounters.delete(tabId);
      console.log(`NetworkCaptureV2: Cleaned up all resources for tab ${tabId}`);
    }
    /**
     * Set up request listeners
     */
    setupListeners() {
      this.listeners.onBeforeRequest = (details) => {
        const captureInfo = this.captureData.get(details.tabId);
        if (!captureInfo) return;
        if (this.shouldFilterRequest(details.url, captureInfo.includeStatic)) {
          return;
        }
        const currentCount = this.requestCounters.get(details.tabId) || 0;
        if (currentCount >= _NetworkCaptureStartTool.MAX_REQUESTS_PER_CAPTURE) {
          console.log(
            `NetworkCaptureV2: Request limit (${_NetworkCaptureStartTool.MAX_REQUESTS_PER_CAPTURE}) reached for tab ${details.tabId}, ignoring new request: ${details.url}`
          );
          captureInfo.limitReached = true;
          return;
        }
        this.requestCounters.set(details.tabId, currentCount + 1);
        this.updateLastActivityTime(details.tabId);
        if (!captureInfo.requests[details.requestId]) {
          captureInfo.requests[details.requestId] = {
            requestId: details.requestId,
            url: details.url,
            method: details.method,
            type: details.type,
            requestTime: details.timeStamp
          };
          if (details.requestBody) {
            const requestBody = this.processRequestBody(details.requestBody);
            if (requestBody) {
              captureInfo.requests[details.requestId].requestBody = requestBody;
            }
          }
          console.log(
            `NetworkCaptureV2: Captured request ${currentCount + 1}/${_NetworkCaptureStartTool.MAX_REQUESTS_PER_CAPTURE} for tab ${details.tabId}: ${details.method} ${details.url}`
          );
        }
      };
      this.listeners.onSendHeaders = (details) => {
        const captureInfo = this.captureData.get(details.tabId);
        if (!captureInfo || !captureInfo.requests[details.requestId]) return;
        if (details.requestHeaders) {
          const headers = {};
          details.requestHeaders.forEach((header) => {
            headers[header.name] = header.value || "";
          });
          captureInfo.requests[details.requestId].requestHeaders = headers;
        }
      };
      this.listeners.onHeadersReceived = (details) => {
        var _a3, _b2;
        const captureInfo = this.captureData.get(details.tabId);
        if (!captureInfo || !captureInfo.requests[details.requestId]) return;
        const requestInfo = captureInfo.requests[details.requestId];
        requestInfo.status = details.statusCode;
        requestInfo.statusText = details.statusLine;
        requestInfo.responseTime = details.timeStamp;
        requestInfo.mimeType = (_b2 = (_a3 = details.responseHeaders) == null ? void 0 : _a3.find(
          (h) => h.name.toLowerCase() === "content-type"
        )) == null ? void 0 : _b2.value;
        if (requestInfo.mimeType && this.shouldFilterByMimeType(requestInfo.mimeType, captureInfo.includeStatic)) {
          delete captureInfo.requests[details.requestId];
          const currentCount = this.requestCounters.get(details.tabId) || 0;
          if (currentCount > 0) {
            this.requestCounters.set(details.tabId, currentCount - 1);
          }
          console.log(
            `NetworkCaptureV2: Filtered request by MIME type (${requestInfo.mimeType}): ${requestInfo.url}`
          );
          return;
        }
        if (details.responseHeaders) {
          const headers = {};
          details.responseHeaders.forEach((header) => {
            headers[header.name] = header.value || "";
          });
          requestInfo.responseHeaders = headers;
        }
        this.updateLastActivityTime(details.tabId);
      };
      this.listeners.onCompleted = (details) => {
        const captureInfo = this.captureData.get(details.tabId);
        if (!captureInfo || !captureInfo.requests[details.requestId]) return;
        const requestInfo = captureInfo.requests[details.requestId];
        if ("responseSize" in details) {
          requestInfo.responseSize = details.fromCache ? 0 : details.responseSize;
        }
        this.updateLastActivityTime(details.tabId);
      };
      this.listeners.onErrorOccurred = (details) => {
        const captureInfo = this.captureData.get(details.tabId);
        if (!captureInfo || !captureInfo.requests[details.requestId]) return;
        const requestInfo = captureInfo.requests[details.requestId];
        requestInfo.errorText = details.error;
        this.updateLastActivityTime(details.tabId);
      };
      chrome.webRequest.onBeforeRequest.addListener(
        this.listeners.onBeforeRequest,
        { urls: ["<all_urls>"] },
        ["requestBody"]
      );
      chrome.webRequest.onSendHeaders.addListener(
        this.listeners.onSendHeaders,
        { urls: ["<all_urls>"] },
        ["requestHeaders"]
      );
      chrome.webRequest.onHeadersReceived.addListener(
        this.listeners.onHeadersReceived,
        { urls: ["<all_urls>"] },
        ["responseHeaders"]
      );
      chrome.webRequest.onCompleted.addListener(this.listeners.onCompleted, { urls: ["<all_urls>"] });
      chrome.webRequest.onErrorOccurred.addListener(this.listeners.onErrorOccurred, {
        urls: ["<all_urls>"]
      });
    }
    /**
     * Remove all request listeners
     * Only remove listeners when all tab captures have stopped
     */
    removeListeners() {
      if (this.captureData.size > 0) {
        console.log(
          `NetworkCaptureV2: Still capturing on ${this.captureData.size} tabs, not removing listeners.`
        );
        return;
      }
      console.log(`NetworkCaptureV2: No more active captures, removing all listeners.`);
      if (this.listeners.onBeforeRequest) {
        chrome.webRequest.onBeforeRequest.removeListener(this.listeners.onBeforeRequest);
      }
      if (this.listeners.onSendHeaders) {
        chrome.webRequest.onSendHeaders.removeListener(this.listeners.onSendHeaders);
      }
      if (this.listeners.onHeadersReceived) {
        chrome.webRequest.onHeadersReceived.removeListener(this.listeners.onHeadersReceived);
      }
      if (this.listeners.onCompleted) {
        chrome.webRequest.onCompleted.removeListener(this.listeners.onCompleted);
      }
      if (this.listeners.onErrorOccurred) {
        chrome.webRequest.onErrorOccurred.removeListener(this.listeners.onErrorOccurred);
      }
      this.listeners = {};
    }
    /**
     * Process request body data
     */
    processRequestBody(requestBody) {
      if (requestBody.raw && requestBody.raw.length > 0) {
        return "[Binary data]";
      } else if (requestBody.formData) {
        return JSON.stringify(requestBody.formData);
      }
      return void 0;
    }
    /**
     * Start network request capture for specified tab
     * @param tabId Tab ID
     * @param options Capture options
     */
    startCaptureForTab(tabId, options) {
      return __async(this, null, function* () {
        const { maxCaptureTime, inactivityTimeout, includeStatic } = options;
        if (this.captureData.has(tabId)) {
          console.log(
            `NetworkCaptureV2: Already capturing on tab ${tabId}. Stopping previous session.`
          );
          yield this.stopCapture(tabId);
        }
        try {
          const tab = yield chrome.tabs.get(tabId);
          this.captureData.set(tabId, {
            tabId,
            tabUrl: tab.url || "",
            tabTitle: tab.title || "",
            startTime: Date.now(),
            requests: {},
            maxCaptureTime,
            inactivityTimeout,
            includeStatic,
            limitReached: false
          });
          this.requestCounters.set(tabId, 0);
          this.setupListeners();
          this.updateLastActivityTime(tabId);
          console.log(
            `NetworkCaptureV2: Started capture for tab ${tabId} (${tab.url}). Max requests: ${_NetworkCaptureStartTool.MAX_REQUESTS_PER_CAPTURE}, Max time: ${maxCaptureTime}ms, Inactivity: ${inactivityTimeout}ms.`
          );
          if (maxCaptureTime > 0) {
            this.captureTimers.set(
              tabId,
              setTimeout(() => __async(this, null, function* () {
                console.log(
                  `NetworkCaptureV2: Max capture time (${maxCaptureTime}ms) reached for tab ${tabId}.`
                );
                yield this.stopCapture(tabId);
              }), maxCaptureTime)
            );
          }
        } catch (error2) {
          console.error(`NetworkCaptureV2: Error starting capture for tab ${tabId}:`, error2);
          if (this.captureData.has(tabId)) {
            this.cleanupCapture(tabId);
          }
          throw error2;
        }
      });
    }
    /**
     * Stop capture
     * @param tabId Tab ID
     */
    stopCapture(tabId) {
      return __async(this, null, function* () {
        const captureInfo = this.captureData.get(tabId);
        if (!captureInfo) {
          console.log(`NetworkCaptureV2: No capture in progress for tab ${tabId}`);
          return { success: false, message: `No capture in progress for tab ${tabId}` };
        }
        try {
          captureInfo.endTime = Date.now();
          const requestsArray = Object.values(captureInfo.requests);
          const commonRequestHeaders = this.analyzeCommonHeaders(requestsArray, "requestHeaders");
          const commonResponseHeaders = this.analyzeCommonHeaders(requestsArray, "responseHeaders");
          const processedRequests = requestsArray.map((req) => {
            const finalReq = __spreadValues({}, req);
            if (finalReq.requestHeaders) {
              finalReq.specificRequestHeaders = this.filterOutCommonHeaders(
                finalReq.requestHeaders,
                commonRequestHeaders
              );
              delete finalReq.requestHeaders;
            } else {
              finalReq.specificRequestHeaders = {};
            }
            if (finalReq.responseHeaders) {
              finalReq.specificResponseHeaders = this.filterOutCommonHeaders(
                finalReq.responseHeaders,
                commonResponseHeaders
              );
              delete finalReq.responseHeaders;
            } else {
              finalReq.specificResponseHeaders = {};
            }
            return finalReq;
          });
          processedRequests.sort((a, b) => (a.requestTime || 0) - (b.requestTime || 0));
          this.removeListeners();
          const resultData = {
            captureStartTime: captureInfo.startTime,
            captureEndTime: captureInfo.endTime,
            totalDurationMs: captureInfo.endTime - captureInfo.startTime,
            settingsUsed: {
              maxCaptureTime: captureInfo.maxCaptureTime,
              inactivityTimeout: captureInfo.inactivityTimeout,
              includeStatic: captureInfo.includeStatic,
              maxRequests: _NetworkCaptureStartTool.MAX_REQUESTS_PER_CAPTURE
            },
            commonRequestHeaders,
            commonResponseHeaders,
            requests: processedRequests,
            requestCount: processedRequests.length,
            totalRequestsReceived: this.requestCounters.get(tabId) || 0,
            requestLimitReached: captureInfo.limitReached || false,
            tabUrl: captureInfo.tabUrl,
            tabTitle: captureInfo.tabTitle
          };
          this.cleanupCapture(tabId);
          return {
            success: true,
            data: resultData
          };
        } catch (error2) {
          console.error(`NetworkCaptureV2: Error stopping capture for tab ${tabId}:`, error2);
          this.cleanupCapture(tabId);
          return {
            success: false,
            message: `Error stopping capture: ${error2.message || String(error2)}`
          };
        }
      });
    }
    /**
     * Analyze common request or response headers
     */
    analyzeCommonHeaders(requests, headerType) {
      if (!requests || requests.length === 0) return {};
      const commonHeaders = {};
      const firstRequestWithHeaders = requests.find(
        (req) => req[headerType] && Object.keys(req[headerType] || {}).length > 0
      );
      if (!firstRequestWithHeaders || !firstRequestWithHeaders[headerType]) {
        return {};
      }
      const headers = firstRequestWithHeaders[headerType];
      const headerNames = Object.keys(headers);
      for (const name2 of headerNames) {
        const value = headers[name2];
        const isCommon = requests.every((req) => {
          const reqHeaders = req[headerType];
          return reqHeaders && reqHeaders[name2] === value;
        });
        if (isCommon) {
          commonHeaders[name2] = value;
        }
      }
      return commonHeaders;
    }
    /**
     * Filter out common headers
     */
    filterOutCommonHeaders(headers, commonHeaders) {
      if (!headers || typeof headers !== "object") return {};
      const specificHeaders = {};
      Object.keys(headers).forEach((name2) => {
        if (!(name2 in commonHeaders) || headers[name2] !== commonHeaders[name2]) {
          specificHeaders[name2] = headers[name2];
        }
      });
      return specificHeaders;
    }
    execute(args) {
      return __async(this, null, function* () {
        const {
          url: targetUrl,
          maxCaptureTime = 3 * 60 * 1e3,
          // Default 3 minutes
          inactivityTimeout = 60 * 1e3,
          // Default 1 minute of inactivity before auto-stop
          includeStatic = false
          // Default: don't include static resources
        } = args;
        console.log(`NetworkCaptureStartTool: Executing with args:`, args);
        try {
          let tabToOperateOn;
          if (targetUrl) {
            const matchingTabs = yield chrome.tabs.query({ url: targetUrl });
            if (matchingTabs.length > 0) {
              tabToOperateOn = matchingTabs[0];
              console.log(`NetworkCaptureV2: Found existing tab with URL: ${targetUrl}`);
            } else {
              console.log(`NetworkCaptureV2: Creating new tab with URL: ${targetUrl}`);
              tabToOperateOn = yield chrome.tabs.create({ url: targetUrl, active: true });
              yield new Promise((resolve2) => setTimeout(resolve2, 1e3));
            }
          } else {
            const tabs = yield chrome.tabs.query({ active: true, currentWindow: true });
            if (!tabs[0]) {
              return createErrorResponse("No active tab found");
            }
            tabToOperateOn = tabs[0];
          }
          if (!(tabToOperateOn == null ? void 0 : tabToOperateOn.id)) {
            return createErrorResponse("Failed to identify or create a tab");
          }
          try {
            yield this.startCaptureForTab(tabToOperateOn.id, {
              maxCaptureTime,
              inactivityTimeout,
              includeStatic
            });
          } catch (error2) {
            return createErrorResponse(
              `Failed to start capture for tab ${tabToOperateOn.id}: ${error2.message || String(error2)}`
            );
          }
          return {
            content: [
              {
                type: "text",
                text: JSON.stringify({
                  success: true,
                  message: "Network capture V2 started successfully, waiting for stop command.",
                  tabId: tabToOperateOn.id,
                  url: tabToOperateOn.url,
                  maxCaptureTime,
                  inactivityTimeout,
                  includeStatic,
                  maxRequests: _NetworkCaptureStartTool.MAX_REQUESTS_PER_CAPTURE
                })
              }
            ],
            isError: false
          };
        } catch (error2) {
          console.error("NetworkCaptureStartTool: Critical error:", error2);
          return createErrorResponse(
            `Error in NetworkCaptureStartTool: ${error2.message || String(error2)}`
          );
        }
      });
    }
  };
  __publicField2(_NetworkCaptureStartTool, "instance", null);
  // tabId -> count of captured requests
  __publicField2(_NetworkCaptureStartTool, "MAX_REQUESTS_PER_CAPTURE", LIMITS$1.MAX_NETWORK_REQUESTS);
  // Static resource MIME types list (for filtering)
  __publicField2(_NetworkCaptureStartTool, "STATIC_MIME_TYPES_TO_FILTER", [
    "image/",
    // All image types
    "font/",
    // All font types
    "audio/",
    // All audio types
    "video/",
    // All video types
    "text/css",
    "text/javascript",
    "application/javascript",
    "application/x-javascript",
    "application/pdf",
    "application/zip",
    "application/octet-stream"
    // Usually for downloads or generic binary data
  ]);
  // API response MIME types list (these types are usually not filtered)
  __publicField2(_NetworkCaptureStartTool, "API_MIME_TYPES", [
    "application/json",
    "application/xml",
    "text/xml",
    "application/x-www-form-urlencoded",
    "application/graphql",
    "application/grpc",
    "application/protobuf",
    "application/x-protobuf",
    "application/x-json",
    "application/ld+json",
    "application/problem+json",
    "application/problem+xml",
    "application/soap+xml",
    "application/vnd.api+json"
  ]);
  let NetworkCaptureStartTool = _NetworkCaptureStartTool;
  const _NetworkCaptureStopTool = class _NetworkCaptureStopTool extends BaseBrowserToolExecutor {
    constructor() {
      super();
      __publicField2(this, "name", TOOL_NAMES.BROWSER.NETWORK_CAPTURE_STOP);
      if (_NetworkCaptureStopTool.instance) {
        return _NetworkCaptureStopTool.instance;
      }
      _NetworkCaptureStopTool.instance = this;
    }
    execute() {
      return __async(this, null, function* () {
        var _a3, _b2, _c2, _d2, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
        console.log(`NetworkCaptureStopTool: Executing`);
        try {
          const startTool = NetworkCaptureStartTool.instance;
          if (!startTool) {
            return createErrorResponse("Network capture V2 start tool instance not found");
          }
          const ongoingCaptures = Array.from(startTool.captureData.keys());
          console.log(
            `NetworkCaptureStopTool: Found ${ongoingCaptures.length} ongoing captures: ${ongoingCaptures.join(", ")}`
          );
          if (ongoingCaptures.length === 0) {
            return createErrorResponse("No active network captures found in any tab.");
          }
          const activeTabs = yield chrome.tabs.query({ active: true, currentWindow: true });
          const activeTabId = (_a3 = activeTabs[0]) == null ? void 0 : _a3.id;
          let primaryTabId;
          if (activeTabId && startTool.captureData.has(activeTabId)) {
            primaryTabId = activeTabId;
            console.log(
              `NetworkCaptureStopTool: Active tab ${activeTabId} is capturing, will stop it first.`
            );
          } else if (ongoingCaptures.length === 1) {
            primaryTabId = ongoingCaptures[0];
            console.log(
              `NetworkCaptureStopTool: Only one tab ${primaryTabId} is capturing, stopping it.`
            );
          } else {
            primaryTabId = ongoingCaptures[0];
            console.log(
              `NetworkCaptureStopTool: Multiple tabs capturing, active tab not among them. Stopping tab ${primaryTabId} first.`
            );
          }
          const stopResult = yield startTool.stopCapture(primaryTabId);
          if (!stopResult.success) {
            return createErrorResponse(
              stopResult.message || `Failed to stop network capture for tab ${primaryTabId}`
            );
          }
          if (ongoingCaptures.length > 1) {
            const otherTabIds = ongoingCaptures.filter((id2) => id2 !== primaryTabId);
            console.log(
              `NetworkCaptureStopTool: Stopping ${otherTabIds.length} additional captures: ${otherTabIds.join(", ")}`
            );
            for (const tabId of otherTabIds) {
              try {
                yield startTool.stopCapture(tabId);
              } catch (error2) {
                console.error(`NetworkCaptureStopTool: Error stopping capture on tab ${tabId}:`, error2);
              }
            }
          }
          return {
            content: [
              {
                type: "text",
                text: JSON.stringify({
                  success: true,
                  message: `Capture complete. ${((_b2 = stopResult.data) == null ? void 0 : _b2.requestCount) || 0} requests captured.`,
                  tabId: primaryTabId,
                  tabUrl: ((_c2 = stopResult.data) == null ? void 0 : _c2.tabUrl) || "N/A",
                  tabTitle: ((_d2 = stopResult.data) == null ? void 0 : _d2.tabTitle) || "Unknown Tab",
                  requestCount: ((_e = stopResult.data) == null ? void 0 : _e.requestCount) || 0,
                  commonRequestHeaders: ((_f = stopResult.data) == null ? void 0 : _f.commonRequestHeaders) || {},
                  commonResponseHeaders: ((_g = stopResult.data) == null ? void 0 : _g.commonResponseHeaders) || {},
                  requests: ((_h = stopResult.data) == null ? void 0 : _h.requests) || [],
                  captureStartTime: (_i = stopResult.data) == null ? void 0 : _i.captureStartTime,
                  captureEndTime: (_j = stopResult.data) == null ? void 0 : _j.captureEndTime,
                  totalDurationMs: (_k = stopResult.data) == null ? void 0 : _k.totalDurationMs,
                  settingsUsed: ((_l = stopResult.data) == null ? void 0 : _l.settingsUsed) || {},
                  totalRequestsReceived: ((_m = stopResult.data) == null ? void 0 : _m.totalRequestsReceived) || 0,
                  requestLimitReached: ((_n = stopResult.data) == null ? void 0 : _n.requestLimitReached) || false,
                  remainingCaptures: Array.from(startTool.captureData.keys())
                })
              }
            ],
            isError: false
          };
        } catch (error2) {
          console.error("NetworkCaptureStopTool: Critical error:", error2);
          return createErrorResponse(
            `Error in NetworkCaptureStopTool: ${error2.message || String(error2)}`
          );
        }
      });
    }
  };
  __publicField2(_NetworkCaptureStopTool, "instance", null);
  let NetworkCaptureStopTool = _NetworkCaptureStopTool;
  const networkCaptureStartTool = new NetworkCaptureStartTool();
  const networkCaptureStopTool = new NetworkCaptureStopTool();
  const injectedTabs = /* @__PURE__ */ new Map();
  class InjectScriptTool extends BaseBrowserToolExecutor {
    constructor() {
      super(...arguments);
      __publicField2(this, "name", TOOL_NAMES.BROWSER.INJECT_SCRIPT);
    }
    execute(args) {
      return __async(this, null, function* () {
        try {
          const { url: url2, type: type2, jsScript } = args;
          let tab;
          if (!type2 || !jsScript) {
            return createErrorResponse("Param [type] and [jsScript] is required");
          }
          if (url2) {
            console.log(`Checking if URL is already open: ${url2}`);
            const allTabs = yield chrome.tabs.query({});
            const matchingTabs = allTabs.filter((t) => {
              var _a3;
              const tabUrl = ((_a3 = t.url) == null ? void 0 : _a3.endsWith("/")) ? t.url.slice(0, -1) : t.url;
              const targetUrl = url2.endsWith("/") ? url2.slice(0, -1) : url2;
              return tabUrl === targetUrl;
            });
            if (matchingTabs.length > 0) {
              tab = matchingTabs[0];
              console.log(`Found existing tab with URL: ${url2}, tab ID: ${tab.id}`);
            } else {
              console.log(`No existing tab found with URL: ${url2}, creating new tab`);
              tab = yield chrome.tabs.create({ url: url2, active: true });
              console.log("Waiting for page to load...");
              yield new Promise((resolve2) => setTimeout(resolve2, 3e3));
            }
          } else {
            const tabs = yield chrome.tabs.query({ active: true });
            if (!tabs[0]) {
              return createErrorResponse("No active tab found");
            }
            tab = tabs[0];
          }
          if (!tab.id) {
            return createErrorResponse("Tab has no ID");
          }
          yield chrome.tabs.update(tab.id, { active: true });
          const res = yield handleInject(tab.id, __spreadValues({}, args));
          return {
            content: [
              {
                type: "text",
                text: JSON.stringify(res)
              }
            ],
            isError: false
          };
        } catch (error2) {
          console.error("Error in InjectScriptTool.execute:", error2);
          return createErrorResponse(
            `Inject script error: ${error2 instanceof Error ? error2.message : String(error2)}`
          );
        }
      });
    }
  }
  class SendCommandToInjectScriptTool extends BaseBrowserToolExecutor {
    constructor() {
      super(...arguments);
      __publicField2(this, "name", TOOL_NAMES.BROWSER.SEND_COMMAND_TO_INJECT_SCRIPT);
    }
    execute(args) {
      return __async(this, null, function* () {
        try {
          const { tabId, eventName, payload } = args;
          if (!eventName) {
            return createErrorResponse("Param [eventName] is required");
          }
          if (tabId) {
            const tabExists = yield isTabExists(tabId);
            if (!tabExists) {
              return createErrorResponse("The tab:[tabId] is not exists");
            }
          }
          let finalTabId = tabId;
          if (finalTabId === void 0) {
            const tabs = yield chrome.tabs.query({ active: true });
            if (!tabs[0]) {
              return createErrorResponse("No active tab found");
            }
            finalTabId = tabs[0].id;
          }
          if (!finalTabId) {
            return createErrorResponse("No active tab found");
          }
          if (!injectedTabs.has(finalTabId)) {
            throw new Error("No script injected in this tab.");
          }
          const result2 = yield chrome.tabs.sendMessage(finalTabId, {
            action: eventName,
            payload,
            targetWorld: injectedTabs.get(finalTabId).type
            // The bridge uses this to decide whether to forward to MAIN world.
          });
          return {
            content: [
              {
                type: "text",
                text: JSON.stringify(result2)
              }
            ],
            isError: false
          };
        } catch (error2) {
          console.error("Error in InjectScriptTool.execute:", error2);
          return createErrorResponse(
            `Inject script error: ${error2 instanceof Error ? error2.message : String(error2)}`
          );
        }
      });
    }
  }
  function isTabExists(tabId) {
    return __async(this, null, function* () {
      try {
        yield chrome.tabs.get(tabId);
        return true;
      } catch (error2) {
        return false;
      }
    });
  }
  function handleInject(tabId, scriptConfig) {
    return __async(this, null, function* () {
      if (injectedTabs.has(tabId)) {
        console.log(`Tab ${tabId} already has injections. Cleaning up first.`);
        yield handleCleanup(tabId);
      }
      const { type: type2, jsScript } = scriptConfig;
      const hasMain = type2 === ExecutionWorld.MAIN;
      if (hasMain) {
        yield chrome.scripting.executeScript({
          target: { tabId },
          files: ["inject-scripts/inject-bridge.js"],
          world: ExecutionWorld.ISOLATED
        });
        yield chrome.scripting.executeScript({
          target: { tabId },
          func: (code2) => new Function(code2)(),
          args: [jsScript],
          world: ExecutionWorld.MAIN
        });
      } else {
        yield chrome.scripting.executeScript({
          target: { tabId },
          func: (code2) => new Function(code2)(),
          args: [jsScript],
          world: ExecutionWorld.ISOLATED
        });
      }
      injectedTabs.set(tabId, scriptConfig);
      console.log(`Scripts successfully injected into tab ${tabId}.`);
      return { injected: true };
    });
  }
  function handleCleanup(tabId) {
    return __async(this, null, function* () {
      if (!injectedTabs.has(tabId)) return;
      chrome.tabs.sendMessage(tabId, { type: "chrome-mcp:cleanup" }).catch(
        (err) => console.warn(`Could not send cleanup message to tab ${tabId}. It might have been closed.`)
      );
      injectedTabs.delete(tabId);
      console.log(`Cleanup signal sent to tab ${tabId}. State cleared.`);
    });
  }
  const injectScriptTool = new InjectScriptTool();
  const sendCommandToInjectScriptTool = new SendCommandToInjectScriptTool();
  chrome.tabs.onRemoved.addListener((tabId) => {
    if (injectedTabs.has(tabId)) {
      console.log(`Tab ${tabId} closed. Cleaning up state.`);
      injectedTabs.delete(tabId);
    }
  });
  const executeScriptSchema = {
    jsScript: string$1().min(1).describe(
      'JavaScript function body as a string. Examples: "() => document.title", "(a, b) => a + b"'
    ),
    args: array(any()).optional().default([]).describe(
      "Array of arguments to pass to the function. These will be serialized and passed to the script."
    ),
    world: _enum$1(["ISOLATED", "MAIN"]).optional().default("ISOLATED").describe(
      "Execution context: ISOLATED (default, safer, extension context) or MAIN (page context, can access page variables)."
    ),
    tabId: number$1().int().positive().optional().describe("Target tab ID. If not provided, uses the currently active tab."),
    timeout: number$1().positive().optional().default(5e3).describe("Timeout in milliseconds for script execution (default: 5000ms).")
  };
  class ExecuteScriptTool extends BaseBrowserToolExecutor {
    constructor() {
      super(...arguments);
      __publicField2(this, "name", TOOL_NAMES.BROWSER.EXECUTE_SCRIPT);
      __publicField2(this, "description", "Execute a JavaScript function in the browser context and synchronously retrieve the result. Unlike chrome_inject_script (which injects persistent code), this tool runs one-time scripts and immediately returns values. Supports both ISOLATED and MAIN execution worlds.");
      __publicField2(this, "annotations", {
        title: "Execute Script",
        category: ToolCategory.DEBUGGING,
        readOnlyHint: false
      });
      __publicField2(this, "schema", executeScriptSchema);
    }
    execute(args) {
      return __async(this, null, function* () {
        var _a3;
        try {
          const validationResult = this.validateArgs(args);
          if (!validationResult.success) {
            return validationResult.error;
          }
          const { jsScript, args: scriptArgs, world, tabId, timeout } = validationResult.data;
          let targetTabId;
          if (tabId) {
            try {
              yield chrome.tabs.get(tabId);
              targetTabId = tabId;
            } catch (err) {
              return error$J(`Tab ${tabId} not found`, "TAB_NOT_FOUND", { tabId });
            }
          } else {
            const tabs = yield chrome.tabs.query({ active: true, currentWindow: true });
            if (!((_a3 = tabs[0]) == null ? void 0 : _a3.id)) {
              return createErrorResponse("No active tab found");
            }
            targetTabId = tabs[0].id;
          }
          const tab = yield chrome.tabs.get(targetTabId);
          const restrictedProtocols = ["chrome://", "chrome-extension://", "edge://", "about:"];
          if (restrictedProtocols.some((protocol) => {
            var _a4;
            return (_a4 = tab.url) == null ? void 0 : _a4.startsWith(protocol);
          })) {
            return error$J(
              `Cannot execute scripts on ${tab.url}. Browser internal pages are restricted.`,
              "PERMISSION_DENIED",
              {
                url: tab.url
              }
            );
          }
          const executionPromise = chrome.scripting.executeScript({
            target: { tabId: targetTabId },
            func: (...args2) => {
              const [code2, ...userArgs] = args2;
              const fn = new Function("...args", `return (${code2})(...args)`);
              return fn(...userArgs);
            },
            args: [jsScript, ...scriptArgs],
            world
          });
          const timeoutPromise = new Promise(
            (_, reject) => setTimeout(() => reject(new Error("Execution timeout")), timeout)
          );
          const results = yield Promise.race([executionPromise, timeoutPromise]);
          if (!results || results.length === 0) {
            return error$J("No execution result returned", "EXECUTION_FAILED");
          }
          const scriptResult = results[0];
          if (scriptResult.error) {
            return error$J(`Script error: ${scriptResult.error}`, "SCRIPT_ERROR", {
              error: scriptResult.error
            });
          }
          try {
            JSON.stringify(scriptResult.result);
          } catch (serializationError) {
            return error$J(
              "Script returned non-serializable value. Please return JSON-compatible data.",
              "SERIALIZATION_ERROR",
              {
                type: typeof scriptResult.result,
                hint: "Return primitive values, arrays, or plain objects only"
              }
            );
          }
          let resultText;
          if (typeof scriptResult.result === "string") {
            resultText = scriptResult.result;
          } else if (scriptResult.result === null || scriptResult.result === void 0) {
            resultText = "Script executed successfully (no return value)";
          } else {
            resultText = JSON.stringify(scriptResult.result, null, 2);
          }
          return success$1(resultText, {
            tabId: targetTabId,
            world
          });
        } catch (err) {
          console.error("Script execution error:", err);
          const errorMessage = err instanceof Error ? err.message : String(err);
          if (errorMessage.includes("timeout")) {
            return error$J("Script execution timed out", "EXECUTION_TIMEOUT", {
              timeout: args.timeout || 5e3
            });
          }
          if (errorMessage.includes("Cannot access")) {
            return error$J("Cannot access this page", "PERMISSION_DENIED");
          }
          return error$J(`Execution failed: ${errorMessage}`, "EXECUTION_FAILED");
        }
      });
    }
  }
  const executeScriptTool = new ExecuteScriptTool();
  const DEBUGGER_PROTOCOL_VERSION$2 = "1.3";
  const DEFAULT_MAX_MESSAGES = 100;
  class ConsoleTool extends BaseBrowserToolExecutor {
    constructor() {
      super(...arguments);
      __publicField2(this, "name", TOOL_NAMES.BROWSER.CONSOLE);
    }
    execute(args) {
      return __async(this, null, function* () {
        const { url: url2, includeExceptions = true, maxMessages = DEFAULT_MAX_MESSAGES } = args;
        let targetTab;
        try {
          if (url2) {
            targetTab = yield this.navigateToUrl(url2);
          } else {
            const [activeTab] = yield chrome.tabs.query({ active: true, currentWindow: true });
            if (!(activeTab == null ? void 0 : activeTab.id)) {
              return createErrorResponse("No active tab found and no URL provided.");
            }
            targetTab = activeTab;
          }
          if (!(targetTab == null ? void 0 : targetTab.id)) {
            return createErrorResponse("Failed to identify target tab.");
          }
          const tabId = targetTab.id;
          const result2 = yield this.captureConsoleMessages(tabId, {
            includeExceptions,
            maxMessages
          });
          return {
            content: [
              {
                type: "text",
                text: JSON.stringify(result2)
              }
            ],
            isError: false
          };
        } catch (error2) {
          console.error("ConsoleTool: Critical error during execute:", error2);
          return createErrorResponse(`Error in ConsoleTool: ${error2.message || String(error2)}`);
        }
      });
    }
    navigateToUrl(url2) {
      return __async(this, null, function* () {
        var _a3;
        const existingTabs = yield chrome.tabs.query({ url: url2 });
        if (existingTabs.length > 0 && ((_a3 = existingTabs[0]) == null ? void 0 : _a3.id)) {
          const tab = existingTabs[0];
          yield chrome.tabs.update(tab.id, { active: true });
          yield chrome.windows.update(tab.windowId, { focused: true });
          return tab;
        } else {
          const newTab = yield chrome.tabs.create({ url: url2, active: true });
          yield this.waitForTabReady(newTab.id);
          return newTab;
        }
      });
    }
    waitForTabReady(tabId) {
      return __async(this, null, function* () {
        return new Promise((resolve2) => {
          const checkTab = () => __async(null, null, function* () {
            try {
              const tab = yield chrome.tabs.get(tabId);
              if (tab.status === "complete") {
                resolve2();
              } else {
                setTimeout(checkTab, 100);
              }
            } catch (error2) {
              resolve2();
            }
          });
          checkTab();
        });
      });
    }
    formatConsoleArgs(args) {
      if (!args || args.length === 0) return "";
      return args.map((arg) => {
        if (arg.type === "string") {
          return arg.value || "";
        } else if (arg.type === "number") {
          return String(arg.value || "");
        } else if (arg.type === "boolean") {
          return String(arg.value || "");
        } else if (arg.type === "object") {
          return arg.description || "[Object]";
        } else if (arg.type === "undefined") {
          return "undefined";
        } else if (arg.type === "function") {
          return arg.description || "[Function]";
        } else {
          return arg.description || arg.value || String(arg);
        }
      }).join(" ");
    }
    captureConsoleMessages(tabId, options) {
      return __async(this, null, function* () {
        var _a3, _b2;
        const { includeExceptions, maxMessages } = options;
        const startTime = Date.now();
        const messages = [];
        const exceptions = [];
        let limitReached = false;
        try {
          const tab = yield chrome.tabs.get(tabId);
          const targets = yield chrome.debugger.getTargets();
          const existingTarget = targets.find(
            (t) => t.tabId === tabId && t.attached && t.type === "page"
          );
          if (existingTarget && !existingTarget.extensionId) {
            throw new Error(
              `Debugger is already attached to tab ${tabId} by another tool (e.g., DevTools).`
            );
          }
          try {
            yield chrome.debugger.attach({ tabId }, DEBUGGER_PROTOCOL_VERSION$2);
          } catch (error2) {
            if ((_a3 = error2.message) == null ? void 0 : _a3.includes("Cannot attach to the target with an attached client")) {
              throw new Error(
                `Debugger is already attached to tab ${tabId}. This might be DevTools or another extension.`
              );
            }
            throw error2;
          }
          const collectedMessages = [];
          const collectedExceptions = [];
          const eventListener = (source, method, params) => {
            var _a4, _b3, _c2, _d2, _e, _f;
            if (source.tabId !== tabId) return;
            if (method === "Log.entryAdded" && (params == null ? void 0 : params.entry)) {
              collectedMessages.push(params.entry);
            } else if (method === "Runtime.consoleAPICalled" && params) {
              const logEntry = {
                timestamp: params.timestamp,
                level: params.type || "log",
                text: this.formatConsoleArgs(params.args || []),
                source: "console-api",
                url: (_c2 = (_b3 = (_a4 = params.stackTrace) == null ? void 0 : _a4.callFrames) == null ? void 0 : _b3[0]) == null ? void 0 : _c2.url,
                lineNumber: (_f = (_e = (_d2 = params.stackTrace) == null ? void 0 : _d2.callFrames) == null ? void 0 : _e[0]) == null ? void 0 : _f.lineNumber,
                stackTrace: params.stackTrace,
                args: params.args
              };
              collectedMessages.push(logEntry);
            } else if (method === "Runtime.exceptionThrown" && includeExceptions && (params == null ? void 0 : params.exceptionDetails)) {
              collectedExceptions.push(params.exceptionDetails);
            }
          };
          chrome.debugger.onEvent.addListener(eventListener);
          try {
            yield chrome.debugger.sendCommand({ tabId }, "Runtime.enable");
            yield chrome.debugger.sendCommand({ tabId }, "Log.enable");
            yield new Promise((resolve2) => setTimeout(resolve2, 2e3));
            for (const entry of collectedMessages) {
              if (messages.length >= maxMessages) {
                limitReached = true;
                break;
              }
              const message = {
                timestamp: entry.timestamp,
                level: entry.level || "log",
                text: entry.text || "",
                source: entry.source,
                url: entry.url,
                lineNumber: entry.lineNumber
              };
              if (entry.stackTrace) {
                message.stackTrace = entry.stackTrace;
              }
              if (entry.args && Array.isArray(entry.args)) {
                message.args = entry.args;
              }
              messages.push(message);
            }
            for (const exceptionDetails of collectedExceptions) {
              const exception = {
                timestamp: Date.now(),
                text: exceptionDetails.text || ((_b2 = exceptionDetails.exception) == null ? void 0 : _b2.description) || "Unknown exception",
                url: exceptionDetails.url,
                lineNumber: exceptionDetails.lineNumber,
                columnNumber: exceptionDetails.columnNumber
              };
              if (exceptionDetails.stackTrace) {
                exception.stackTrace = exceptionDetails.stackTrace;
              }
              exceptions.push(exception);
            }
          } finally {
            chrome.debugger.onEvent.removeListener(eventListener);
            try {
              yield chrome.debugger.sendCommand({ tabId }, "Runtime.disable");
            } catch (e) {
              console.warn(`ConsoleTool: Error disabling Runtime for tab ${tabId}:`, e);
            }
            try {
              yield chrome.debugger.sendCommand({ tabId }, "Log.disable");
            } catch (e) {
              console.warn(`ConsoleTool: Error disabling Log for tab ${tabId}:`, e);
            }
            try {
              yield chrome.debugger.detach({ tabId });
            } catch (e) {
              console.warn(`ConsoleTool: Error detaching debugger for tab ${tabId}:`, e);
            }
          }
          const endTime = Date.now();
          messages.sort((a, b) => a.timestamp - b.timestamp);
          exceptions.sort((a, b) => a.timestamp - b.timestamp);
          return {
            success: true,
            message: `Console capture completed for tab ${tabId}. ${messages.length} messages, ${exceptions.length} exceptions captured.`,
            tabId,
            tabUrl: tab.url || "",
            tabTitle: tab.title || "",
            captureStartTime: startTime,
            captureEndTime: endTime,
            totalDurationMs: endTime - startTime,
            messages,
            exceptions,
            messageCount: messages.length,
            exceptionCount: exceptions.length,
            messageLimitReached: limitReached
          };
        } catch (error2) {
          console.error(`ConsoleTool: Error capturing console messages for tab ${tabId}:`, error2);
          throw error2;
        }
      });
    }
  }
  const consoleTool = new ConsoleTool();
  class PageProtectionEnableTool extends BaseBrowserToolExecutor {
    constructor() {
      super(...arguments);
      __publicField2(this, "name", TOOL_NAMES.BROWSER.PAGE_PROTECTION_ENABLE);
    }
    execute(args) {
      return __async(this, null, function* () {
        var _a3, _b2;
        const { tabId } = args;
        console.log("Enabling page protection with options:", args);
        try {
          let targetTab;
          if (tabId) {
            targetTab = yield chrome.tabs.get(tabId);
          } else {
            const tabs = yield chrome.tabs.query({ active: true, currentWindow: true });
            targetTab = tabs[0];
          }
          if (!targetTab || !targetTab.id) {
            return createErrorResponse(ERROR_MESSAGES.TAB_NOT_FOUND);
          }
          if (((_a3 = targetTab.url) == null ? void 0 : _a3.startsWith("chrome://")) || ((_b2 = targetTab.url) == null ? void 0 : _b2.startsWith("moz-extension://"))) {
            return createErrorResponse("Cannot protect system pages or extension pages");
          }
          yield this.injectContentScript(targetTab.id, ["inject-scripts/page-protection-helper.js"]);
          const result2 = yield this.sendMessageToTabWithTimeout(
            targetTab.id,
            {
              action: "ENABLE_PAGE_PROTECTION"
            },
            5e3
          );
          if (!result2.success) {
            return createErrorResponse(result2.message || "Failed to enable page protection");
          }
          const verificationResult = yield this.sendMessageToTabWithTimeout(
            targetTab.id,
            {
              action: "GET_PROTECTION_STATUS"
            },
            3e3
          );
          const protectionEnabled = (verificationResult == null ? void 0 : verificationResult.protectionEnabled) || false;
          return {
            content: [
              {
                type: "text",
                text: JSON.stringify({
                  success: true,
                  message: "Page protection enabled successfully",
                  tabId: targetTab.id,
                  tabUrl: targetTab.url,
                  tabTitle: targetTab.title,
                  protectionEnabled,
                  verificationStatus: verificationResult ? "verified" : "unable_to_verify"
                })
              }
            ],
            isError: false
          };
        } catch (error2) {
          console.error("Error enabling page protection:", error2);
          return createErrorResponse(
            `Error enabling page protection: ${error2 instanceof Error ? error2.message : String(error2)}`
          );
        }
      });
    }
  }
  class PageProtectionDisableTool extends BaseBrowserToolExecutor {
    constructor() {
      super(...arguments);
      __publicField2(this, "name", TOOL_NAMES.BROWSER.PAGE_PROTECTION_DISABLE);
    }
    execute(args) {
      return __async(this, null, function* () {
        const { tabId } = args;
        console.log("Disabling page protection with options:", args);
        try {
          let targetTab;
          if (tabId) {
            targetTab = yield chrome.tabs.get(tabId);
          } else {
            const tabs = yield chrome.tabs.query({ active: true, currentWindow: true });
            targetTab = tabs[0];
          }
          if (!targetTab || !targetTab.id) {
            return createErrorResponse(ERROR_MESSAGES.TAB_NOT_FOUND);
          }
          let disableResult = null;
          let communicationStatus = "success";
          let errorDetails = "";
          try {
            disableResult = yield this.sendMessageToTabWithTimeout(
              targetTab.id,
              {
                action: "DISABLE_PAGE_PROTECTION"
              },
              5e3
            );
          } catch (error2) {
            communicationStatus = "communication_failed";
            errorDetails = error2 instanceof Error ? error2.message : String(error2);
            console.warn("Failed to communicate with content script for disable:", error2);
          }
          let verificationResult = null;
          try {
            verificationResult = yield this.sendMessageToTabWithTimeout(
              targetTab.id,
              {
                action: "GET_PROTECTION_STATUS"
              },
              3e3
            );
          } catch (error2) {
            console.warn("Failed to verify protection status after disable:", error2);
          }
          const protectionEnabled = (verificationResult == null ? void 0 : verificationResult.protectionEnabled) || false;
          const wasDisabled = (disableResult == null ? void 0 : disableResult.success) || !protectionEnabled;
          return {
            content: [
              {
                type: "text",
                text: JSON.stringify({
                  success: true,
                  message: wasDisabled ? "Page protection disabled successfully" : "Page protection was not enabled",
                  tabId: targetTab.id,
                  tabUrl: targetTab.url,
                  tabTitle: targetTab.title,
                  protectionEnabled,
                  communicationStatus,
                  errorDetails: errorDetails || void 0,
                  verificationStatus: verificationResult ? "verified" : "unable_to_verify"
                })
              }
            ],
            isError: false
          };
        } catch (error2) {
          console.error("Error disabling page protection:", error2);
          return createErrorResponse(
            `Error disabling page protection: ${error2 instanceof Error ? error2.message : String(error2)}`
          );
        }
      });
    }
  }
  class PageProtectionStatusTool extends BaseBrowserToolExecutor {
    constructor() {
      super(...arguments);
      __publicField2(this, "name", TOOL_NAMES.BROWSER.PAGE_PROTECTION_STATUS);
    }
    execute(args) {
      return __async(this, null, function* () {
        const { tabId } = args;
        console.log("Checking page protection status for tab:", tabId || "active tab");
        try {
          let targetTab;
          if (tabId) {
            targetTab = yield chrome.tabs.get(tabId);
          } else {
            const tabs = yield chrome.tabs.query({ active: true, currentWindow: true });
            targetTab = tabs[0];
          }
          if (!targetTab || !targetTab.id) {
            return createErrorResponse(ERROR_MESSAGES.TAB_NOT_FOUND);
          }
          let liveStatus = null;
          let communicationStatus = "success";
          let errorDetails = "";
          try {
            liveStatus = yield this.sendMessageToTabWithTimeout(
              targetTab.id,
              {
                action: "GET_PROTECTION_STATUS"
              },
              5e3
            );
          } catch (error2) {
            communicationStatus = this.classifyCommunicationError(error2);
            errorDetails = error2 instanceof Error ? error2.message : String(error2);
            console.log("Could not get live status from tab:", errorDetails);
          }
          const protectionEnabled = (liveStatus == null ? void 0 : liveStatus.protectionEnabled) || null;
          let statusDescription = "";
          if (liveStatus && liveStatus.success) {
            statusDescription = protectionEnabled ? "Page protection is active" : "Page protection is not active";
          } else {
            switch (communicationStatus) {
              case "script_missing":
                statusDescription = "Protection script not injected - page is unprotected";
                break;
              case "tab_unresponsive":
                statusDescription = "Cannot communicate with tab - protection status unknown";
                break;
              case "permission_denied":
                statusDescription = "Permission denied to access tab - cannot check protection";
                break;
              case "timeout":
                statusDescription = "Communication timeout - protection status uncertain";
                break;
              default:
                statusDescription = "Unknown communication error - protection status uncertain";
            }
          }
          return {
            content: [
              {
                type: "text",
                text: JSON.stringify({
                  success: true,
                  tabId: targetTab.id,
                  tabUrl: targetTab.url,
                  tabTitle: targetTab.title,
                  protectionEnabled,
                  communicationStatus,
                  statusDescription,
                  liveProtectionStatus: liveStatus,
                  errorDetails: errorDetails || void 0,
                  timestamp: Date.now()
                })
              }
            ],
            isError: false
          };
        } catch (error2) {
          console.error("Error checking page protection status:", error2);
          return createErrorResponse(
            `Error checking page protection status: ${error2 instanceof Error ? error2.message : String(error2)}`
          );
        }
      });
    }
  }
  const pageProtectionEnableTool = new PageProtectionEnableTool();
  const pageProtectionDisableTool = new PageProtectionDisableTool();
  const pageProtectionStatusTool = new PageProtectionStatusTool();
  class HighlightElementsTool extends BaseBrowserToolExecutor {
    constructor() {
      super(...arguments);
      __publicField2(this, "name", TOOL_NAMES.BROWSER.HIGHLIGHT_ELEMENTS);
    }
    execute(args) {
      return __async(this, null, function* () {
        var _a3;
        try {
          const targetTab = args.tabId ? yield chrome.tabs.get(args.tabId) : (yield chrome.tabs.query({ active: true, currentWindow: true }))[0];
          if (!targetTab || !targetTab.id) {
            return createErrorResponse("No active tab found or invalid tab ID");
          }
          const tabId = targetTab.id;
          yield this.injectContentScript(tabId, ["inject-scripts/highlight-injector.js"]);
          const results = yield this.sendMessageToTab(tabId, {
            action: "HIGHLIGHT_ELEMENTS",
            selector: args.selector || null
          });
          if (!results || !results.success) {
            return createErrorResponse(
              "Failed to highlight elements - no response from content script"
            );
          }
          const highlightedCount = ((_a3 = results.highlightedElements) == null ? void 0 : _a3.length) || 0;
          return {
            content: [
              {
                type: "text",
                text: `Successfully highlighted ${highlightedCount} interactive elements on the page${args.selector ? ` matching selector: ${args.selector}` : ""}. Elements are numbered and show confidence levels when hovered.`
              }
            ],
            isError: false
          };
        } catch (error2) {
          console.error("Highlight elements error:", error2);
          return createErrorResponse(`Failed to highlight elements: ${error2.message}`);
        }
      });
    }
  }
  class RemoveHighlightsTool extends BaseBrowserToolExecutor {
    constructor() {
      super(...arguments);
      __publicField2(this, "name", TOOL_NAMES.BROWSER.REMOVE_HIGHLIGHTS);
    }
    execute(args) {
      return __async(this, null, function* () {
        try {
          const targetTab = args.tabId ? yield chrome.tabs.get(args.tabId) : (yield chrome.tabs.query({ active: true, currentWindow: true }))[0];
          if (!targetTab || !targetTab.id) {
            return createErrorResponse("No active tab found or invalid tab ID");
          }
          const tabId = targetTab.id;
          yield this.sendMessageToTab(tabId, {
            action: "REMOVE_HIGHLIGHTS"
          });
          return {
            content: [
              {
                type: "text",
                text: "Successfully removed all highlighting elements from the page."
              }
            ],
            isError: false
          };
        } catch (error2) {
          console.error("Remove highlights error:", error2);
          return createErrorResponse(`Failed to remove highlights: ${error2.message}`);
        }
      });
    }
  }
  const highlightElementsTool = new HighlightElementsTool();
  const removeHighlightsTool = new RemoveHighlightsTool();
  function createImageBitmapFromUrl(dataUrl) {
    return __async(this, null, function* () {
      const response = yield fetch(dataUrl);
      const blob = yield response.blob();
      return yield createImageBitmap(blob);
    });
  }
  function compressImage(imageDataUrl, options) {
    return __async(this, null, function* () {
      const { scale = 1, quality = 0.8, format: format2 = "image/jpeg" } = options;
      const imageBitmap = yield createImageBitmapFromUrl(imageDataUrl);
      const newWidth = Math.round(imageBitmap.width * scale);
      const newHeight = Math.round(imageBitmap.height * scale);
      const canvas = new OffscreenCanvas(newWidth, newHeight);
      const ctx = canvas.getContext("2d");
      if (!ctx) {
        throw new Error("Failed to get 2D context from OffscreenCanvas");
      }
      ctx.drawImage(imageBitmap, 0, 0, newWidth, newHeight);
      const compressedDataUrl = yield canvas.convertToBlob({ type: format2, quality });
      const dataUrl = yield new Promise((resolve2) => {
        const reader = new FileReader();
        reader.onloadend = () => resolve2(reader.result);
        reader.readAsDataURL(compressedDataUrl);
      });
      return { dataUrl, mimeType: format2 };
    });
  }
  var react = { exports: {} };
  function getDefaultExportFromCjs(x) {
    return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
  }
  var browser = { exports: {} };
  var process = browser.exports = {};
  var cachedSetTimeout;
  var cachedClearTimeout;
  function defaultSetTimout() {
    throw new Error("setTimeout has not been defined");
  }
  function defaultClearTimeout() {
    throw new Error("clearTimeout has not been defined");
  }
  (function() {
    try {
      if (typeof setTimeout === "function") {
        cachedSetTimeout = setTimeout;
      } else {
        cachedSetTimeout = defaultSetTimout;
      }
    } catch (e) {
      cachedSetTimeout = defaultSetTimout;
    }
    try {
      if (typeof clearTimeout === "function") {
        cachedClearTimeout = clearTimeout;
      } else {
        cachedClearTimeout = defaultClearTimeout;
      }
    } catch (e) {
      cachedClearTimeout = defaultClearTimeout;
    }
  })();
  function runTimeout(fun) {
    if (cachedSetTimeout === setTimeout) {
      return setTimeout(fun, 0);
    }
    if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
      cachedSetTimeout = setTimeout;
      return setTimeout(fun, 0);
    }
    try {
      return cachedSetTimeout(fun, 0);
    } catch (e) {
      try {
        return cachedSetTimeout.call(null, fun, 0);
      } catch (e2) {
        return cachedSetTimeout.call(this, fun, 0);
      }
    }
  }
  function runClearTimeout(marker) {
    if (cachedClearTimeout === clearTimeout) {
      return clearTimeout(marker);
    }
    if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
      cachedClearTimeout = clearTimeout;
      return clearTimeout(marker);
    }
    try {
      return cachedClearTimeout(marker);
    } catch (e) {
      try {
        return cachedClearTimeout.call(null, marker);
      } catch (e2) {
        return cachedClearTimeout.call(this, marker);
      }
    }
  }
  var queue = [];
  var draining = false;
  var currentQueue;
  var queueIndex = -1;
  function cleanUpNextTick() {
    if (!draining || !currentQueue) {
      return;
    }
    draining = false;
    if (currentQueue.length) {
      queue = currentQueue.concat(queue);
    } else {
      queueIndex = -1;
    }
    if (queue.length) {
      drainQueue();
    }
  }
  function drainQueue() {
    if (draining) {
      return;
    }
    var timeout = runTimeout(cleanUpNextTick);
    draining = true;
    var len2 = queue.length;
    while (len2) {
      currentQueue = queue;
      queue = [];
      while (++queueIndex < len2) {
        if (currentQueue) {
          currentQueue[queueIndex].run();
        }
      }
      queueIndex = -1;
      len2 = queue.length;
    }
    currentQueue = null;
    draining = false;
    runClearTimeout(timeout);
  }
  process.nextTick = function(fun) {
    var args = new Array(arguments.length - 1);
    if (arguments.length > 1) {
      for (var i2 = 1; i2 < arguments.length; i2++) {
        args[i2 - 1] = arguments[i2];
      }
    }
    queue.push(new Item(fun, args));
    if (queue.length === 1 && !draining) {
      runTimeout(drainQueue);
    }
  };
  function Item(fun, array2) {
    this.fun = fun;
    this.array = array2;
  }
  Item.prototype.run = function() {
    this.fun.apply(null, this.array);
  };
  process.title = "browser";
  process.browser = true;
  process.env = {};
  process.argv = [];
  process.version = "";
  process.versions = {};
  function noop() {
  }
  process.on = noop;
  process.addListener = noop;
  process.once = noop;
  process.off = noop;
  process.removeListener = noop;
  process.removeAllListeners = noop;
  process.emit = noop;
  process.prependListener = noop;
  process.prependOnceListener = noop;
  process.listeners = function(name2) {
    return [];
  };
  process.binding = function(name2) {
    throw new Error("process.binding is not supported");
  };
  process.cwd = function() {
    return "/";
  };
  process.chdir = function(dir) {
    throw new Error("process.chdir is not supported");
  };
  process.umask = function() {
    return 0;
  };
  var browserExports = browser.exports;
  const process$1 = /* @__PURE__ */ getDefaultExportFromCjs(browserExports);
  var react_production = {};
  var hasRequiredReact_production;
  function requireReact_production() {
    if (hasRequiredReact_production) return react_production;
    hasRequiredReact_production = 1;
    var REACT_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = /* @__PURE__ */ Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = /* @__PURE__ */ Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = /* @__PURE__ */ Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = /* @__PURE__ */ Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = /* @__PURE__ */ Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = /* @__PURE__ */ Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = /* @__PURE__ */ Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = /* @__PURE__ */ Symbol.for("react.suspense"), REACT_MEMO_TYPE = /* @__PURE__ */ Symbol.for("react.memo"), REACT_LAZY_TYPE = /* @__PURE__ */ Symbol.for("react.lazy"), REACT_ACTIVITY_TYPE = /* @__PURE__ */ Symbol.for("react.activity"), MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
    function getIteratorFn(maybeIterable) {
      if (null === maybeIterable || "object" !== typeof maybeIterable) return null;
      maybeIterable = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable["@@iterator"];
      return "function" === typeof maybeIterable ? maybeIterable : null;
    }
    var ReactNoopUpdateQueue = {
      isMounted: function() {
        return false;
      },
      enqueueForceUpdate: function() {
      },
      enqueueReplaceState: function() {
      },
      enqueueSetState: function() {
      }
    }, assign = Object.assign, emptyObject = {};
    function Component(props, context, updater) {
      this.props = props;
      this.context = context;
      this.refs = emptyObject;
      this.updater = updater || ReactNoopUpdateQueue;
    }
    Component.prototype.isReactComponent = {};
    Component.prototype.setState = function(partialState, callback) {
      if ("object" !== typeof partialState && "function" !== typeof partialState && null != partialState)
        throw Error(
          "takes an object of state variables to update or a function which returns an object of state variables."
        );
      this.updater.enqueueSetState(this, partialState, callback, "setState");
    };
    Component.prototype.forceUpdate = function(callback) {
      this.updater.enqueueForceUpdate(this, callback, "forceUpdate");
    };
    function ComponentDummy() {
    }
    ComponentDummy.prototype = Component.prototype;
    function PureComponent(props, context, updater) {
      this.props = props;
      this.context = context;
      this.refs = emptyObject;
      this.updater = updater || ReactNoopUpdateQueue;
    }
    var pureComponentPrototype = PureComponent.prototype = new ComponentDummy();
    pureComponentPrototype.constructor = PureComponent;
    assign(pureComponentPrototype, Component.prototype);
    pureComponentPrototype.isPureReactComponent = true;
    var isArrayImpl = Array.isArray;
    function noop2() {
    }
    var ReactSharedInternals = { H: null, A: null, T: null, S: null }, hasOwnProperty = Object.prototype.hasOwnProperty;
    function ReactElement(type2, key, props) {
      var refProp = props.ref;
      return {
        $$typeof: REACT_ELEMENT_TYPE,
        type: type2,
        key,
        ref: void 0 !== refProp ? refProp : null,
        props
      };
    }
    function cloneAndReplaceKey(oldElement, newKey) {
      return ReactElement(oldElement.type, newKey, oldElement.props);
    }
    function isValidElement(object2) {
      return "object" === typeof object2 && null !== object2 && object2.$$typeof === REACT_ELEMENT_TYPE;
    }
    function escape2(key) {
      var escaperLookup = { "=": "=0", ":": "=2" };
      return "$" + key.replace(/[=:]/g, function(match) {
        return escaperLookup[match];
      });
    }
    var userProvidedKeyEscapeRegex = /\/+/g;
    function getElementKey(element, index2) {
      return "object" === typeof element && null !== element && null != element.key ? escape2("" + element.key) : index2.toString(36);
    }
    function resolveThenable(thenable) {
      switch (thenable.status) {
        case "fulfilled":
          return thenable.value;
        case "rejected":
          throw thenable.reason;
        default:
          switch ("string" === typeof thenable.status ? thenable.then(noop2, noop2) : (thenable.status = "pending", thenable.then(
            function(fulfilledValue) {
              "pending" === thenable.status && (thenable.status = "fulfilled", thenable.value = fulfilledValue);
            },
            function(error2) {
              "pending" === thenable.status && (thenable.status = "rejected", thenable.reason = error2);
            }
          )), thenable.status) {
            case "fulfilled":
              return thenable.value;
            case "rejected":
              throw thenable.reason;
          }
      }
      throw thenable;
    }
    function mapIntoArray(children, array2, escapedPrefix, nameSoFar, callback) {
      var type2 = typeof children;
      if ("undefined" === type2 || "boolean" === type2) children = null;
      var invokeCallback = false;
      if (null === children) invokeCallback = true;
      else
        switch (type2) {
          case "bigint":
          case "string":
          case "number":
            invokeCallback = true;
            break;
          case "object":
            switch (children.$$typeof) {
              case REACT_ELEMENT_TYPE:
              case REACT_PORTAL_TYPE:
                invokeCallback = true;
                break;
              case REACT_LAZY_TYPE:
                return invokeCallback = children._init, mapIntoArray(
                  invokeCallback(children._payload),
                  array2,
                  escapedPrefix,
                  nameSoFar,
                  callback
                );
            }
        }
      if (invokeCallback)
        return callback = callback(children), invokeCallback = "" === nameSoFar ? "." + getElementKey(children, 0) : nameSoFar, isArrayImpl(callback) ? (escapedPrefix = "", null != invokeCallback && (escapedPrefix = invokeCallback.replace(userProvidedKeyEscapeRegex, "$&/") + "/"), mapIntoArray(callback, array2, escapedPrefix, "", function(c) {
          return c;
        })) : null != callback && (isValidElement(callback) && (callback = cloneAndReplaceKey(
          callback,
          escapedPrefix + (null == callback.key || children && children.key === callback.key ? "" : ("" + callback.key).replace(
            userProvidedKeyEscapeRegex,
            "$&/"
          ) + "/") + invokeCallback
        )), array2.push(callback)), 1;
      invokeCallback = 0;
      var nextNamePrefix = "" === nameSoFar ? "." : nameSoFar + ":";
      if (isArrayImpl(children))
        for (var i2 = 0; i2 < children.length; i2++)
          nameSoFar = children[i2], type2 = nextNamePrefix + getElementKey(nameSoFar, i2), invokeCallback += mapIntoArray(
            nameSoFar,
            array2,
            escapedPrefix,
            type2,
            callback
          );
      else if (i2 = getIteratorFn(children), "function" === typeof i2)
        for (children = i2.call(children), i2 = 0; !(nameSoFar = children.next()).done; )
          nameSoFar = nameSoFar.value, type2 = nextNamePrefix + getElementKey(nameSoFar, i2++), invokeCallback += mapIntoArray(
            nameSoFar,
            array2,
            escapedPrefix,
            type2,
            callback
          );
      else if ("object" === type2) {
        if ("function" === typeof children.then)
          return mapIntoArray(
            resolveThenable(children),
            array2,
            escapedPrefix,
            nameSoFar,
            callback
          );
        array2 = String(children);
        throw Error(
          "Objects are not valid as a React child (found: " + ("[object Object]" === array2 ? "object with keys {" + Object.keys(children).join(", ") + "}" : array2) + "). If you meant to render a collection of children, use an array instead."
        );
      }
      return invokeCallback;
    }
    function mapChildren(children, func, context) {
      if (null == children) return children;
      var result2 = [], count = 0;
      mapIntoArray(children, result2, "", "", function(child) {
        return func.call(context, child, count++);
      });
      return result2;
    }
    function lazyInitializer(payload) {
      if (-1 === payload._status) {
        var ctor = payload._result;
        ctor = ctor();
        ctor.then(
          function(moduleObject) {
            if (0 === payload._status || -1 === payload._status)
              payload._status = 1, payload._result = moduleObject;
          },
          function(error2) {
            if (0 === payload._status || -1 === payload._status)
              payload._status = 2, payload._result = error2;
          }
        );
        -1 === payload._status && (payload._status = 0, payload._result = ctor);
      }
      if (1 === payload._status) return payload._result.default;
      throw payload._result;
    }
    var reportGlobalError = "function" === typeof reportError ? reportError : function(error2) {
      if ("object" === typeof window && "function" === typeof window.ErrorEvent) {
        var event = new window.ErrorEvent("error", {
          bubbles: true,
          cancelable: true,
          message: "object" === typeof error2 && null !== error2 && "string" === typeof error2.message ? String(error2.message) : String(error2),
          error: error2
        });
        if (!window.dispatchEvent(event)) return;
      } else if ("object" === typeof process$1 && "function" === typeof process$1.emit) {
        process$1.emit("uncaughtException", error2);
        return;
      }
      console.error(error2);
    }, Children = {
      map: mapChildren,
      forEach: function(children, forEachFunc, forEachContext) {
        mapChildren(
          children,
          function() {
            forEachFunc.apply(this, arguments);
          },
          forEachContext
        );
      },
      count: function(children) {
        var n = 0;
        mapChildren(children, function() {
          n++;
        });
        return n;
      },
      toArray: function(children) {
        return mapChildren(children, function(child) {
          return child;
        }) || [];
      },
      only: function(children) {
        if (!isValidElement(children))
          throw Error(
            "React.Children.only expected to receive a single React element child."
          );
        return children;
      }
    };
    react_production.Activity = REACT_ACTIVITY_TYPE;
    react_production.Children = Children;
    react_production.Component = Component;
    react_production.Fragment = REACT_FRAGMENT_TYPE;
    react_production.Profiler = REACT_PROFILER_TYPE;
    react_production.PureComponent = PureComponent;
    react_production.StrictMode = REACT_STRICT_MODE_TYPE;
    react_production.Suspense = REACT_SUSPENSE_TYPE;
    react_production.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = ReactSharedInternals;
    react_production.__COMPILER_RUNTIME = {
      __proto__: null,
      c: function(size) {
        return ReactSharedInternals.H.useMemoCache(size);
      }
    };
    react_production.cache = function(fn) {
      return function() {
        return fn.apply(null, arguments);
      };
    };
    react_production.cacheSignal = function() {
      return null;
    };
    react_production.cloneElement = function(element, config2, children) {
      if (null === element || void 0 === element)
        throw Error(
          "The argument must be a React element, but you passed " + element + "."
        );
      var props = assign({}, element.props), key = element.key;
      if (null != config2)
        for (propName in void 0 !== config2.key && (key = "" + config2.key), config2)
          !hasOwnProperty.call(config2, propName) || "key" === propName || "__self" === propName || "__source" === propName || "ref" === propName && void 0 === config2.ref || (props[propName] = config2[propName]);
      var propName = arguments.length - 2;
      if (1 === propName) props.children = children;
      else if (1 < propName) {
        for (var childArray = Array(propName), i2 = 0; i2 < propName; i2++)
          childArray[i2] = arguments[i2 + 2];
        props.children = childArray;
      }
      return ReactElement(element.type, key, props);
    };
    react_production.createContext = function(defaultValue) {
      defaultValue = {
        $$typeof: REACT_CONTEXT_TYPE,
        _currentValue: defaultValue,
        _currentValue2: defaultValue,
        _threadCount: 0,
        Provider: null,
        Consumer: null
      };
      defaultValue.Provider = defaultValue;
      defaultValue.Consumer = {
        $$typeof: REACT_CONSUMER_TYPE,
        _context: defaultValue
      };
      return defaultValue;
    };
    react_production.createElement = function(type2, config2, children) {
      var propName, props = {}, key = null;
      if (null != config2)
        for (propName in void 0 !== config2.key && (key = "" + config2.key), config2)
          hasOwnProperty.call(config2, propName) && "key" !== propName && "__self" !== propName && "__source" !== propName && (props[propName] = config2[propName]);
      var childrenLength = arguments.length - 2;
      if (1 === childrenLength) props.children = children;
      else if (1 < childrenLength) {
        for (var childArray = Array(childrenLength), i2 = 0; i2 < childrenLength; i2++)
          childArray[i2] = arguments[i2 + 2];
        props.children = childArray;
      }
      if (type2 && type2.defaultProps)
        for (propName in childrenLength = type2.defaultProps, childrenLength)
          void 0 === props[propName] && (props[propName] = childrenLength[propName]);
      return ReactElement(type2, key, props);
    };
    react_production.createRef = function() {
      return { current: null };
    };
    react_production.forwardRef = function(render) {
      return { $$typeof: REACT_FORWARD_REF_TYPE, render };
    };
    react_production.isValidElement = isValidElement;
    react_production.lazy = function(ctor) {
      return {
        $$typeof: REACT_LAZY_TYPE,
        _payload: { _status: -1, _result: ctor },
        _init: lazyInitializer
      };
    };
    react_production.memo = function(type2, compare) {
      return {
        $$typeof: REACT_MEMO_TYPE,
        type: type2,
        compare: void 0 === compare ? null : compare
      };
    };
    react_production.startTransition = function(scope2) {
      var prevTransition = ReactSharedInternals.T, currentTransition = {};
      ReactSharedInternals.T = currentTransition;
      try {
        var returnValue = scope2(), onStartTransitionFinish = ReactSharedInternals.S;
        null !== onStartTransitionFinish && onStartTransitionFinish(currentTransition, returnValue);
        "object" === typeof returnValue && null !== returnValue && "function" === typeof returnValue.then && returnValue.then(noop2, reportGlobalError);
      } catch (error2) {
        reportGlobalError(error2);
      } finally {
        null !== prevTransition && null !== currentTransition.types && (prevTransition.types = currentTransition.types), ReactSharedInternals.T = prevTransition;
      }
    };
    react_production.unstable_useCacheRefresh = function() {
      return ReactSharedInternals.H.useCacheRefresh();
    };
    react_production.use = function(usable) {
      return ReactSharedInternals.H.use(usable);
    };
    react_production.useActionState = function(action, initialState, permalink) {
      return ReactSharedInternals.H.useActionState(action, initialState, permalink);
    };
    react_production.useCallback = function(callback, deps) {
      return ReactSharedInternals.H.useCallback(callback, deps);
    };
    react_production.useContext = function(Context) {
      return ReactSharedInternals.H.useContext(Context);
    };
    react_production.useDebugValue = function() {
    };
    react_production.useDeferredValue = function(value, initialValue) {
      return ReactSharedInternals.H.useDeferredValue(value, initialValue);
    };
    react_production.useEffect = function(create2, deps) {
      return ReactSharedInternals.H.useEffect(create2, deps);
    };
    react_production.useEffectEvent = function(callback) {
      return ReactSharedInternals.H.useEffectEvent(callback);
    };
    react_production.useId = function() {
      return ReactSharedInternals.H.useId();
    };
    react_production.useImperativeHandle = function(ref2, create2, deps) {
      return ReactSharedInternals.H.useImperativeHandle(ref2, create2, deps);
    };
    react_production.useInsertionEffect = function(create2, deps) {
      return ReactSharedInternals.H.useInsertionEffect(create2, deps);
    };
    react_production.useLayoutEffect = function(create2, deps) {
      return ReactSharedInternals.H.useLayoutEffect(create2, deps);
    };
    react_production.useMemo = function(create2, deps) {
      return ReactSharedInternals.H.useMemo(create2, deps);
    };
    react_production.useOptimistic = function(passthrough, reducer) {
      return ReactSharedInternals.H.useOptimistic(passthrough, reducer);
    };
    react_production.useReducer = function(reducer, initialArg, init) {
      return ReactSharedInternals.H.useReducer(reducer, initialArg, init);
    };
    react_production.useRef = function(initialValue) {
      return ReactSharedInternals.H.useRef(initialValue);
    };
    react_production.useState = function(initialState) {
      return ReactSharedInternals.H.useState(initialState);
    };
    react_production.useSyncExternalStore = function(subscribe, getSnapshot, getServerSnapshot) {
      return ReactSharedInternals.H.useSyncExternalStore(
        subscribe,
        getSnapshot,
        getServerSnapshot
      );
    };
    react_production.useTransition = function() {
      return ReactSharedInternals.H.useTransition();
    };
    react_production.version = "19.2.3";
    return react_production;
  }
  var hasRequiredReact;
  function requireReact() {
    if (hasRequiredReact) return react.exports;
    hasRequiredReact = 1;
    {
      react.exports = requireReact_production();
    }
    return react.exports;
  }
  var reactExports = requireReact();
  const React = /* @__PURE__ */ getDefaultExportFromCjs$1(reactExports);
  var reactDom = { exports: {} };
  var reactDom_production = {};
  var hasRequiredReactDom_production;
  function requireReactDom_production() {
    if (hasRequiredReactDom_production) return reactDom_production;
    hasRequiredReactDom_production = 1;
    var React2 = requireReact();
    function formatProdErrorMessage(code2) {
      var url2 = "https://react.dev/errors/" + code2;
      if (1 < arguments.length) {
        url2 += "?args[]=" + encodeURIComponent(arguments[1]);
        for (var i2 = 2; i2 < arguments.length; i2++)
          url2 += "&args[]=" + encodeURIComponent(arguments[i2]);
      }
      return "Minified React error #" + code2 + "; visit " + url2 + " for the full message or use the non-minified dev environment for full errors and additional helpful warnings.";
    }
    function noop2() {
    }
    var Internals = {
      d: {
        f: noop2,
        r: function() {
          throw Error(formatProdErrorMessage(522));
        },
        D: noop2,
        C: noop2,
        L: noop2,
        m: noop2,
        X: noop2,
        S: noop2,
        M: noop2
      },
      p: 0,
      findDOMNode: null
    }, REACT_PORTAL_TYPE = /* @__PURE__ */ Symbol.for("react.portal");
    function createPortal$1(children, containerInfo, implementation) {
      var key = 3 < arguments.length && void 0 !== arguments[3] ? arguments[3] : null;
      return {
        $$typeof: REACT_PORTAL_TYPE,
        key: null == key ? null : "" + key,
        children,
        containerInfo,
        implementation
      };
    }
    var ReactSharedInternals = React2.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;
    function getCrossOriginStringAs(as, input) {
      if ("font" === as) return "";
      if ("string" === typeof input)
        return "use-credentials" === input ? input : "";
    }
    reactDom_production.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = Internals;
    reactDom_production.createPortal = function(children, container) {
      var key = 2 < arguments.length && void 0 !== arguments[2] ? arguments[2] : null;
      if (!container || 1 !== container.nodeType && 9 !== container.nodeType && 11 !== container.nodeType)
        throw Error(formatProdErrorMessage(299));
      return createPortal$1(children, container, null, key);
    };
    reactDom_production.flushSync = function(fn) {
      var previousTransition = ReactSharedInternals.T, previousUpdatePriority = Internals.p;
      try {
        if (ReactSharedInternals.T = null, Internals.p = 2, fn) return fn();
      } finally {
        ReactSharedInternals.T = previousTransition, Internals.p = previousUpdatePriority, Internals.d.f();
      }
    };
    reactDom_production.preconnect = function(href, options) {
      "string" === typeof href && (options ? (options = options.crossOrigin, options = "string" === typeof options ? "use-credentials" === options ? options : "" : void 0) : options = null, Internals.d.C(href, options));
    };
    reactDom_production.prefetchDNS = function(href) {
      "string" === typeof href && Internals.d.D(href);
    };
    reactDom_production.preinit = function(href, options) {
      if ("string" === typeof href && options && "string" === typeof options.as) {
        var as = options.as, crossOrigin = getCrossOriginStringAs(as, options.crossOrigin), integrity = "string" === typeof options.integrity ? options.integrity : void 0, fetchPriority = "string" === typeof options.fetchPriority ? options.fetchPriority : void 0;
        "style" === as ? Internals.d.S(
          href,
          "string" === typeof options.precedence ? options.precedence : void 0,
          {
            crossOrigin,
            integrity,
            fetchPriority
          }
        ) : "script" === as && Internals.d.X(href, {
          crossOrigin,
          integrity,
          fetchPriority,
          nonce: "string" === typeof options.nonce ? options.nonce : void 0
        });
      }
    };
    reactDom_production.preinitModule = function(href, options) {
      if ("string" === typeof href)
        if ("object" === typeof options && null !== options) {
          if (null == options.as || "script" === options.as) {
            var crossOrigin = getCrossOriginStringAs(
              options.as,
              options.crossOrigin
            );
            Internals.d.M(href, {
              crossOrigin,
              integrity: "string" === typeof options.integrity ? options.integrity : void 0,
              nonce: "string" === typeof options.nonce ? options.nonce : void 0
            });
          }
        } else null == options && Internals.d.M(href);
    };
    reactDom_production.preload = function(href, options) {
      if ("string" === typeof href && "object" === typeof options && null !== options && "string" === typeof options.as) {
        var as = options.as, crossOrigin = getCrossOriginStringAs(as, options.crossOrigin);
        Internals.d.L(href, as, {
          crossOrigin,
          integrity: "string" === typeof options.integrity ? options.integrity : void 0,
          nonce: "string" === typeof options.nonce ? options.nonce : void 0,
          type: "string" === typeof options.type ? options.type : void 0,
          fetchPriority: "string" === typeof options.fetchPriority ? options.fetchPriority : void 0,
          referrerPolicy: "string" === typeof options.referrerPolicy ? options.referrerPolicy : void 0,
          imageSrcSet: "string" === typeof options.imageSrcSet ? options.imageSrcSet : void 0,
          imageSizes: "string" === typeof options.imageSizes ? options.imageSizes : void 0,
          media: "string" === typeof options.media ? options.media : void 0
        });
      }
    };
    reactDom_production.preloadModule = function(href, options) {
      if ("string" === typeof href)
        if (options) {
          var crossOrigin = getCrossOriginStringAs(options.as, options.crossOrigin);
          Internals.d.m(href, {
            as: "string" === typeof options.as && "script" !== options.as ? options.as : void 0,
            crossOrigin,
            integrity: "string" === typeof options.integrity ? options.integrity : void 0
          });
        } else Internals.d.m(href);
    };
    reactDom_production.requestFormReset = function(form) {
      Internals.d.r(form);
    };
    reactDom_production.unstable_batchedUpdates = function(fn, a) {
      return fn(a);
    };
    reactDom_production.useFormState = function(action, initialState, permalink) {
      return ReactSharedInternals.H.useFormState(action, initialState, permalink);
    };
    reactDom_production.useFormStatus = function() {
      return ReactSharedInternals.H.useHostTransitionStatus();
    };
    reactDom_production.version = "19.2.3";
    return reactDom_production;
  }
  var hasRequiredReactDom;
  function requireReactDom() {
    if (hasRequiredReactDom) return reactDom.exports;
    hasRequiredReactDom = 1;
    function checkDCE() {
      if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === "undefined" || typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== "function") {
        return;
      }
      try {
        __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE);
      } catch (err) {
        console.error(err);
      }
    }
    {
      checkDCE();
      reactDom.exports = requireReactDom_production();
    }
    return reactDom.exports;
  }
  requireReactDom();
  function __insertCSS(code2) {
    if (typeof document == "undefined") return;
    let head = document.head || document.getElementsByTagName("head")[0];
    let style = document.createElement("style");
    style.type = "text/css";
    head.appendChild(style);
    style.styleSheet ? style.styleSheet.cssText = code2 : style.appendChild(document.createTextNode(code2));
  }
  Array(12).fill(0);
  let toastsCounter = 1;
  class Observer {
    constructor() {
      this.subscribe = (subscriber) => {
        this.subscribers.push(subscriber);
        return () => {
          const index2 = this.subscribers.indexOf(subscriber);
          this.subscribers.splice(index2, 1);
        };
      };
      this.publish = (data) => {
        this.subscribers.forEach((subscriber) => subscriber(data));
      };
      this.addToast = (data) => {
        this.publish(data);
        this.toasts = [
          ...this.toasts,
          data
        ];
      };
      this.create = (data) => {
        var _data_id;
        const _a3 = data, { message } = _a3, rest = __objRest(_a3, ["message"]);
        const id2 = typeof (data == null ? void 0 : data.id) === "number" || ((_data_id = data.id) == null ? void 0 : _data_id.length) > 0 ? data.id : toastsCounter++;
        const alreadyExists = this.toasts.find((toast2) => {
          return toast2.id === id2;
        });
        const dismissible = data.dismissible === void 0 ? true : data.dismissible;
        if (this.dismissedToasts.has(id2)) {
          this.dismissedToasts.delete(id2);
        }
        if (alreadyExists) {
          this.toasts = this.toasts.map((toast2) => {
            if (toast2.id === id2) {
              this.publish(__spreadProps(__spreadValues(__spreadValues({}, toast2), data), {
                id: id2,
                title: message
              }));
              return __spreadProps(__spreadValues(__spreadValues({}, toast2), data), {
                id: id2,
                dismissible,
                title: message
              });
            }
            return toast2;
          });
        } else {
          this.addToast(__spreadProps(__spreadValues({
            title: message
          }, rest), {
            dismissible,
            id: id2
          }));
        }
        return id2;
      };
      this.dismiss = (id2) => {
        if (id2) {
          this.dismissedToasts.add(id2);
          requestAnimationFrame(() => this.subscribers.forEach((subscriber) => subscriber({
            id: id2,
            dismiss: true
          })));
        } else {
          this.toasts.forEach((toast2) => {
            this.subscribers.forEach((subscriber) => subscriber({
              id: toast2.id,
              dismiss: true
            }));
          });
        }
        return id2;
      };
      this.message = (message, data) => {
        return this.create(__spreadProps(__spreadValues({}, data), {
          message
        }));
      };
      this.error = (message, data) => {
        return this.create(__spreadProps(__spreadValues({}, data), {
          message,
          type: "error"
        }));
      };
      this.success = (message, data) => {
        return this.create(__spreadProps(__spreadValues({}, data), {
          type: "success",
          message
        }));
      };
      this.info = (message, data) => {
        return this.create(__spreadProps(__spreadValues({}, data), {
          type: "info",
          message
        }));
      };
      this.warning = (message, data) => {
        return this.create(__spreadProps(__spreadValues({}, data), {
          type: "warning",
          message
        }));
      };
      this.loading = (message, data) => {
        return this.create(__spreadProps(__spreadValues({}, data), {
          type: "loading",
          message
        }));
      };
      this.promise = (promise2, data) => {
        if (!data) {
          return;
        }
        let id2 = void 0;
        if (data.loading !== void 0) {
          id2 = this.create(__spreadProps(__spreadValues({}, data), {
            promise: promise2,
            type: "loading",
            message: data.loading,
            description: typeof data.description !== "function" ? data.description : void 0
          }));
        }
        const p = Promise.resolve(promise2 instanceof Function ? promise2() : promise2);
        let shouldDismiss = id2 !== void 0;
        let result2;
        const originalPromise = p.then((response) => __async(this, null, function* () {
          result2 = [
            "resolve",
            response
          ];
          const isReactElementResponse = React.isValidElement(response);
          if (isReactElementResponse) {
            shouldDismiss = false;
            this.create({
              id: id2,
              type: "default",
              message: response
            });
          } else if (isHttpResponse(response) && !response.ok) {
            shouldDismiss = false;
            const promiseData = typeof data.error === "function" ? yield data.error(`HTTP error! status: ${response.status}`) : data.error;
            const description2 = typeof data.description === "function" ? yield data.description(`HTTP error! status: ${response.status}`) : data.description;
            const isExtendedResult = typeof promiseData === "object" && !React.isValidElement(promiseData);
            const toastSettings = isExtendedResult ? promiseData : {
              message: promiseData
            };
            this.create(__spreadValues({
              id: id2,
              type: "error",
              description: description2
            }, toastSettings));
          } else if (response instanceof Error) {
            shouldDismiss = false;
            const promiseData = typeof data.error === "function" ? yield data.error(response) : data.error;
            const description2 = typeof data.description === "function" ? yield data.description(response) : data.description;
            const isExtendedResult = typeof promiseData === "object" && !React.isValidElement(promiseData);
            const toastSettings = isExtendedResult ? promiseData : {
              message: promiseData
            };
            this.create(__spreadValues({
              id: id2,
              type: "error",
              description: description2
            }, toastSettings));
          } else if (data.success !== void 0) {
            shouldDismiss = false;
            const promiseData = typeof data.success === "function" ? yield data.success(response) : data.success;
            const description2 = typeof data.description === "function" ? yield data.description(response) : data.description;
            const isExtendedResult = typeof promiseData === "object" && !React.isValidElement(promiseData);
            const toastSettings = isExtendedResult ? promiseData : {
              message: promiseData
            };
            this.create(__spreadValues({
              id: id2,
              type: "success",
              description: description2
            }, toastSettings));
          }
        })).catch((error2) => __async(this, null, function* () {
          result2 = [
            "reject",
            error2
          ];
          if (data.error !== void 0) {
            shouldDismiss = false;
            const promiseData = typeof data.error === "function" ? yield data.error(error2) : data.error;
            const description2 = typeof data.description === "function" ? yield data.description(error2) : data.description;
            const isExtendedResult = typeof promiseData === "object" && !React.isValidElement(promiseData);
            const toastSettings = isExtendedResult ? promiseData : {
              message: promiseData
            };
            this.create(__spreadValues({
              id: id2,
              type: "error",
              description: description2
            }, toastSettings));
          }
        })).finally(() => {
          if (shouldDismiss) {
            this.dismiss(id2);
            id2 = void 0;
          }
          data.finally == null ? void 0 : data.finally.call(data);
        });
        const unwrap = () => new Promise((resolve2, reject) => originalPromise.then(() => result2[0] === "reject" ? reject(result2[1]) : resolve2(result2[1])).catch(reject));
        if (typeof id2 !== "string" && typeof id2 !== "number") {
          return {
            unwrap
          };
        } else {
          return Object.assign(id2, {
            unwrap
          });
        }
      };
      this.custom = (jsx, data) => {
        const id2 = (data == null ? void 0 : data.id) || toastsCounter++;
        this.create(__spreadValues({
          jsx: jsx(id2),
          id: id2
        }, data));
        return id2;
      };
      this.getActiveToasts = () => {
        return this.toasts.filter((toast2) => !this.dismissedToasts.has(toast2.id));
      };
      this.subscribers = [];
      this.toasts = [];
      this.dismissedToasts = /* @__PURE__ */ new Set();
    }
  }
  const ToastState = new Observer();
  const toastFunction = (message, data) => {
    const id2 = (data == null ? void 0 : data.id) || toastsCounter++;
    ToastState.addToast(__spreadProps(__spreadValues({
      title: message
    }, data), {
      id: id2
    }));
    return id2;
  };
  const isHttpResponse = (data) => {
    return data && typeof data === "object" && "ok" in data && typeof data.ok === "boolean" && "status" in data && typeof data.status === "number";
  };
  const basicToast = toastFunction;
  const getHistory = () => ToastState.toasts;
  const getToasts = () => ToastState.getActiveToasts();
  const toast = Object.assign(basicToast, {
    success: ToastState.success,
    info: ToastState.info,
    warning: ToastState.warning,
    error: ToastState.error,
    custom: ToastState.custom,
    message: ToastState.message,
    promise: ToastState.promise,
    dismiss: ToastState.dismiss,
    loading: ToastState.loading
  }, {
    getHistory,
    getToasts
  });
  __insertCSS("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");
  const __vite_import_meta_env__$1 = { "BASE_URL": "/", "BROWSER": "chrome", "CHROME": true, "COMMAND": "build", "DEV": false, "EDGE": false, "ENTRYPOINT": "background", "FIREFOX": false, "MANIFEST_VERSION": 3, "MODE": "production", "OPERA": false, "PROD": true, "SAFARI": false, "SSR": false, "VITE_API_BASE_URL": "https://datasaver.deepminingai.com/api", "VITE_API_BASE_URL_V1": "https://datasaver.deepminingai.com/api", "VITE_CHROME_EXTENSION_KEY": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz6mSqF9xmKhi3zThuAi5f/Kf+U0C9GWHfEJuf7M57pQ+ybkNiAX2M+XI5UdiFhw8d7Wpmk2rQ72bKGiZDgyV47qe9ntEAO+kF/mPWuoEfhFpvRsb+MzOwiCzLgCHo2FGfeVq+Y38fk/vEi21OSm+MHdKy03ud3a0X9C5c+5ser23e8RKXf5Y2ZrYTPn3kgex+GyhfaKceYDxkq/CkDTnVwUnoDAfm9vhoaJZ4GqQ69rSasOSm4WjdKiIWJbhDZl96ECl/FdUkHnO56rQCkWqSF3Fb9XqJuIz9lHo6PHp44LCNE2hOv7C9UjQpMjVtNx2ynM/sUEJHhOUzhixPdVtKQIDAQAB", "VITE_CHROME_EXTENSION_KEY_POPUP": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3xXBvP+mtfJ1giQcRAco9aEFz8FNwceqOVj9EQkv9It6PoMlnNrpWz1RhzpeXpaFiBbM9Exs+QFL0BQIivzbSkIe/kziMFJdhCryiA5pZZAQSfEKpF8lpleh9BNX2U6HRnwb6s8RGQ9/inrvTAzuZeRIXeHD2/tpGOJV3MLjzPnntcEKTP8A1SfOkHtFS1YOB5jPd/9OR/kpCFL1kpREO/rGvHChIhR3jL0s96KYesyse4ItDRWuAHeNYj1eyCoRjVeSBqm3Ma2uN75xxPED7p/FHej4OaNF0VAiH+z8RRguQl+qFAIEH0NCs5T/eVu9n4dIhesKUZYdpRRJxRo/zwIDAQAB", "VITE_DM_URL": "https://v1.deepminer.ai", "VITE_IMAGE_TYPE": "base64" };
  const DEFAULT_API_BASE_URL$1 = "https://datasaver.deepminingai.com/api";
  function getApiBaseUrl$1(version2) {
    return __async(this, null, function* () {
      try {
        if (version2) {
          return (__vite_import_meta_env__$1 == null ? void 0 : __vite_import_meta_env__$1[`VITE_API_BASE_URL_${String(version2).toUpperCase()}`]) || DEFAULT_API_BASE_URL$1;
        }
        return DEFAULT_API_BASE_URL$1;
      } catch (error2) {
        console.error("Failed to get API base URL:", error2);
        return DEFAULT_API_BASE_URL$1;
      }
    });
  }
  function getExtensionVersion$1() {
    try {
      return chrome.runtime.getManifest().version;
    } catch (error2) {
      console.error("获取 Extension 版本号失败:", error2);
      return "";
    }
  }
  const getToolCNName = (name2) => {
    switch (name2) {
      case "submit_and_poll_extraction":
      case "poll_extraction_task":
      case "submit_extraction_task":
        return "生成取数脚本";
      case "save_mano_extraction_file":
        return "生成数据文件";
      default:
        return name2;
    }
  };
  function getExtensionVersion() {
    try {
      return chrome.runtime.getManifest().version;
    } catch (error2) {
      console.error("获取 Extension 版本号失败:", error2);
      return "";
    }
  }
  function encodeSpaceMetadata(metadata2) {
    if (!(metadata2 == null ? void 0 : metadata2.id) || !(metadata2 == null ? void 0 : metadata2.name)) {
      return "";
    }
    try {
      const jsonString = JSON.stringify(__spreadValues(__spreadValues({
        id: metadata2.id,
        name: metadata2.name
      }, metadata2.subject_id && { subject_id: metadata2.subject_id }), metadata2.feature_key && { feature_key: metadata2.feature_key }));
      const utf8Bytes = new TextEncoder().encode(jsonString);
      const binaryString = Array.from(utf8Bytes, (byte) => String.fromCharCode(byte)).join("");
      return btoa(binaryString);
    } catch (error2) {
      console.error("Failed to encode space metadata:", error2);
      return "";
    }
  }
  const LIMITS = {
    MAX_NETWORK_REQUESTS: 100,
    MAX_SEARCH_RESULTS: 50,
    MAX_BOOKMARK_RESULTS: 100,
    MAX_HISTORY_RESULTS: 100,
    SIMILARITY_THRESHOLD: 0.1,
    VECTOR_DIMENSIONS: 384
  };
  const TODO_TOOL_NAME = "TodoWrite";
  const FE_TOOLS_PREFIX = "fe__tools__";
  const TOOL_TODOLIST = "todoList";
  const MANO_SAVE_FILE = "mcp__mano__save_mano_extraction_file";
  const MANO_SUBMIT_TASK = "mcp__mano__submit_extraction_task";
  const TASK = "Task";
  const SKILL = "Skill";
  const CREATE_WORKFLOW = "mcp__skills__create_workflow";
  const REPORT_WORKFLOW_PROGRESS = "mcp__skills__report_workflow_progress";
  const ASK_HUMAN = "mcp__user_interaction_tools__ask_user_confirmation";
  const CAPTURE_REQUEST_PREFIX = "captured-requests-";
  const BACKGROUND_MESSAGE_TYPES = {
    SWITCH_SEMANTIC_MODEL: "switch_semantic_model",
    GET_MODEL_STATUS: "get_model_status",
    UPDATE_MODEL_STATUS: "update_model_status",
    GET_STORAGE_STATS: "get_storage_stats",
    CLEAR_ALL_DATA: "clear_all_data",
    GET_SERVER_STATUS: "get_server_status",
    REFRESH_SERVER_STATUS: "refresh_server_status",
    SERVER_STATUS_CHANGED: "server_status_changed",
    INITIALIZE_SEMANTIC_ENGINE: "initialize_semantic_engine",
    GET_WEBSOCKET_LATENCY_METRICS: "get_websocket_latency_metrics",
    TRIGGER_WEBSOCKET_LATENCY_TEST: "trigger_websocket_latency_test",
    WEBSOCKET_LATENCY_UPDATED: "websocket_latency_updated",
    FETCH_IMAGE_URL: "fetch_image_url",
    // MCP 执行日志相关
    GET_MCP_LOG_STATS: "get_mcp_log_stats",
    QUERY_MCP_LOGS: "query_mcp_logs",
    CLEAR_MCP_LOGS: "clear_mcp_logs",
    CLEANUP_MCP_LOGS: "cleanup_mcp_logs",
    // 自动网络请求捕获相关
    START_AUTO_CAPTURE: "start_auto_capture",
    STOP_AUTO_CAPTURE: "stop_auto_capture",
    GET_CAPTURED_REQUESTS: "get_captured_requests",
    GET_SUCCESSFUL_REQUESTS: "get_successful_requests",
    GET_CAPTURE_STATS: "get_capture_stats",
    CLEAR_CAPTURED_REQUESTS: "clear_captured_requests",
    GET_AUTO_CAPTURE_STATUS: "get_auto_capture_status",
    PREVIEW_REQUEST: "preview_request"
    // 预览指定请求
  };
  var dayjs_min$1 = { exports: {} };
  var dayjs_min = dayjs_min$1.exports;
  var hasRequiredDayjs_min;
  function requireDayjs_min() {
    if (hasRequiredDayjs_min) return dayjs_min$1.exports;
    hasRequiredDayjs_min = 1;
    (function(module2, exports$12) {
      !(function(t, e) {
        module2.exports = e();
      })(dayjs_min, (function() {
        var t = 1e3, e = 6e4, n = 36e5, r = "millisecond", i2 = "second", s = "minute", u = "hour", a = "day", o = "week", c = "month", f = "quarter", h = "year", d = "date", l = "Invalid Date", $ = /^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/, y = /\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g, M = { name: "en", weekdays: "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), months: "January_February_March_April_May_June_July_August_September_October_November_December".split("_"), ordinal: function(t2) {
          var e2 = ["th", "st", "nd", "rd"], n2 = t2 % 100;
          return "[" + t2 + (e2[(n2 - 20) % 10] || e2[n2] || e2[0]) + "]";
        } }, m = function(t2, e2, n2) {
          var r2 = String(t2);
          return !r2 || r2.length >= e2 ? t2 : "" + Array(e2 + 1 - r2.length).join(n2) + t2;
        }, v = { s: m, z: function(t2) {
          var e2 = -t2.utcOffset(), n2 = Math.abs(e2), r2 = Math.floor(n2 / 60), i3 = n2 % 60;
          return (e2 <= 0 ? "+" : "-") + m(r2, 2, "0") + ":" + m(i3, 2, "0");
        }, m: function t2(e2, n2) {
          if (e2.date() < n2.date()) return -t2(n2, e2);
          var r2 = 12 * (n2.year() - e2.year()) + (n2.month() - e2.month()), i3 = e2.clone().add(r2, c), s2 = n2 - i3 < 0, u2 = e2.clone().add(r2 + (s2 ? -1 : 1), c);
          return +(-(r2 + (n2 - i3) / (s2 ? i3 - u2 : u2 - i3)) || 0);
        }, a: function(t2) {
          return t2 < 0 ? Math.ceil(t2) || 0 : Math.floor(t2);
        }, p: function(t2) {
          return { M: c, y: h, w: o, d: a, D: d, h: u, m: s, s: i2, ms: r, Q: f }[t2] || String(t2 || "").toLowerCase().replace(/s$/, "");
        }, u: function(t2) {
          return void 0 === t2;
        } }, g = "en", D = {};
        D[g] = M;
        var p = "$isDayjsObject", S = function(t2) {
          return t2 instanceof _ || !(!t2 || !t2[p]);
        }, w = function t2(e2, n2, r2) {
          var i3;
          if (!e2) return g;
          if ("string" == typeof e2) {
            var s2 = e2.toLowerCase();
            D[s2] && (i3 = s2), n2 && (D[s2] = n2, i3 = s2);
            var u2 = e2.split("-");
            if (!i3 && u2.length > 1) return t2(u2[0]);
          } else {
            var a2 = e2.name;
            D[a2] = e2, i3 = a2;
          }
          return !r2 && i3 && (g = i3), i3 || !r2 && g;
        }, O = function(t2, e2) {
          if (S(t2)) return t2.clone();
          var n2 = "object" == typeof e2 ? e2 : {};
          return n2.date = t2, n2.args = arguments, new _(n2);
        }, b = v;
        b.l = w, b.i = S, b.w = function(t2, e2) {
          return O(t2, { locale: e2.$L, utc: e2.$u, x: e2.$x, $offset: e2.$offset });
        };
        var _ = (function() {
          function M2(t2) {
            this.$L = w(t2.locale, null, true), this.parse(t2), this.$x = this.$x || t2.x || {}, this[p] = true;
          }
          var m2 = M2.prototype;
          return m2.parse = function(t2) {
            this.$d = (function(t3) {
              var e2 = t3.date, n2 = t3.utc;
              if (null === e2) return /* @__PURE__ */ new Date(NaN);
              if (b.u(e2)) return /* @__PURE__ */ new Date();
              if (e2 instanceof Date) return new Date(e2);
              if ("string" == typeof e2 && !/Z$/i.test(e2)) {
                var r2 = e2.match($);
                if (r2) {
                  var i3 = r2[2] - 1 || 0, s2 = (r2[7] || "0").substring(0, 3);
                  return n2 ? new Date(Date.UTC(r2[1], i3, r2[3] || 1, r2[4] || 0, r2[5] || 0, r2[6] || 0, s2)) : new Date(r2[1], i3, r2[3] || 1, r2[4] || 0, r2[5] || 0, r2[6] || 0, s2);
                }
              }
              return new Date(e2);
            })(t2), this.init();
          }, m2.init = function() {
            var t2 = this.$d;
            this.$y = t2.getFullYear(), this.$M = t2.getMonth(), this.$D = t2.getDate(), this.$W = t2.getDay(), this.$H = t2.getHours(), this.$m = t2.getMinutes(), this.$s = t2.getSeconds(), this.$ms = t2.getMilliseconds();
          }, m2.$utils = function() {
            return b;
          }, m2.isValid = function() {
            return !(this.$d.toString() === l);
          }, m2.isSame = function(t2, e2) {
            var n2 = O(t2);
            return this.startOf(e2) <= n2 && n2 <= this.endOf(e2);
          }, m2.isAfter = function(t2, e2) {
            return O(t2) < this.startOf(e2);
          }, m2.isBefore = function(t2, e2) {
            return this.endOf(e2) < O(t2);
          }, m2.$g = function(t2, e2, n2) {
            return b.u(t2) ? this[e2] : this.set(n2, t2);
          }, m2.unix = function() {
            return Math.floor(this.valueOf() / 1e3);
          }, m2.valueOf = function() {
            return this.$d.getTime();
          }, m2.startOf = function(t2, e2) {
            var n2 = this, r2 = !!b.u(e2) || e2, f2 = b.p(t2), l2 = function(t3, e3) {
              var i3 = b.w(n2.$u ? Date.UTC(n2.$y, e3, t3) : new Date(n2.$y, e3, t3), n2);
              return r2 ? i3 : i3.endOf(a);
            }, $2 = function(t3, e3) {
              return b.w(n2.toDate()[t3].apply(n2.toDate("s"), (r2 ? [0, 0, 0, 0] : [23, 59, 59, 999]).slice(e3)), n2);
            }, y2 = this.$W, M3 = this.$M, m3 = this.$D, v2 = "set" + (this.$u ? "UTC" : "");
            switch (f2) {
              case h:
                return r2 ? l2(1, 0) : l2(31, 11);
              case c:
                return r2 ? l2(1, M3) : l2(0, M3 + 1);
              case o:
                var g2 = this.$locale().weekStart || 0, D2 = (y2 < g2 ? y2 + 7 : y2) - g2;
                return l2(r2 ? m3 - D2 : m3 + (6 - D2), M3);
              case a:
              case d:
                return $2(v2 + "Hours", 0);
              case u:
                return $2(v2 + "Minutes", 1);
              case s:
                return $2(v2 + "Seconds", 2);
              case i2:
                return $2(v2 + "Milliseconds", 3);
              default:
                return this.clone();
            }
          }, m2.endOf = function(t2) {
            return this.startOf(t2, false);
          }, m2.$set = function(t2, e2) {
            var n2, o2 = b.p(t2), f2 = "set" + (this.$u ? "UTC" : ""), l2 = (n2 = {}, n2[a] = f2 + "Date", n2[d] = f2 + "Date", n2[c] = f2 + "Month", n2[h] = f2 + "FullYear", n2[u] = f2 + "Hours", n2[s] = f2 + "Minutes", n2[i2] = f2 + "Seconds", n2[r] = f2 + "Milliseconds", n2)[o2], $2 = o2 === a ? this.$D + (e2 - this.$W) : e2;
            if (o2 === c || o2 === h) {
              var y2 = this.clone().set(d, 1);
              y2.$d[l2]($2), y2.init(), this.$d = y2.set(d, Math.min(this.$D, y2.daysInMonth())).$d;
            } else l2 && this.$d[l2]($2);
            return this.init(), this;
          }, m2.set = function(t2, e2) {
            return this.clone().$set(t2, e2);
          }, m2.get = function(t2) {
            return this[b.p(t2)]();
          }, m2.add = function(r2, f2) {
            var d2, l2 = this;
            r2 = Number(r2);
            var $2 = b.p(f2), y2 = function(t2) {
              var e2 = O(l2);
              return b.w(e2.date(e2.date() + Math.round(t2 * r2)), l2);
            };
            if ($2 === c) return this.set(c, this.$M + r2);
            if ($2 === h) return this.set(h, this.$y + r2);
            if ($2 === a) return y2(1);
            if ($2 === o) return y2(7);
            var M3 = (d2 = {}, d2[s] = e, d2[u] = n, d2[i2] = t, d2)[$2] || 1, m3 = this.$d.getTime() + r2 * M3;
            return b.w(m3, this);
          }, m2.subtract = function(t2, e2) {
            return this.add(-1 * t2, e2);
          }, m2.format = function(t2) {
            var e2 = this, n2 = this.$locale();
            if (!this.isValid()) return n2.invalidDate || l;
            var r2 = t2 || "YYYY-MM-DDTHH:mm:ssZ", i3 = b.z(this), s2 = this.$H, u2 = this.$m, a2 = this.$M, o2 = n2.weekdays, c2 = n2.months, f2 = n2.meridiem, h2 = function(t3, n3, i4, s3) {
              return t3 && (t3[n3] || t3(e2, r2)) || i4[n3].slice(0, s3);
            }, d2 = function(t3) {
              return b.s(s2 % 12 || 12, t3, "0");
            }, $2 = f2 || function(t3, e3, n3) {
              var r3 = t3 < 12 ? "AM" : "PM";
              return n3 ? r3.toLowerCase() : r3;
            };
            return r2.replace(y, (function(t3, r3) {
              return r3 || (function(t4) {
                switch (t4) {
                  case "YY":
                    return String(e2.$y).slice(-2);
                  case "YYYY":
                    return b.s(e2.$y, 4, "0");
                  case "M":
                    return a2 + 1;
                  case "MM":
                    return b.s(a2 + 1, 2, "0");
                  case "MMM":
                    return h2(n2.monthsShort, a2, c2, 3);
                  case "MMMM":
                    return h2(c2, a2);
                  case "D":
                    return e2.$D;
                  case "DD":
                    return b.s(e2.$D, 2, "0");
                  case "d":
                    return String(e2.$W);
                  case "dd":
                    return h2(n2.weekdaysMin, e2.$W, o2, 2);
                  case "ddd":
                    return h2(n2.weekdaysShort, e2.$W, o2, 3);
                  case "dddd":
                    return o2[e2.$W];
                  case "H":
                    return String(s2);
                  case "HH":
                    return b.s(s2, 2, "0");
                  case "h":
                    return d2(1);
                  case "hh":
                    return d2(2);
                  case "a":
                    return $2(s2, u2, true);
                  case "A":
                    return $2(s2, u2, false);
                  case "m":
                    return String(u2);
                  case "mm":
                    return b.s(u2, 2, "0");
                  case "s":
                    return String(e2.$s);
                  case "ss":
                    return b.s(e2.$s, 2, "0");
                  case "SSS":
                    return b.s(e2.$ms, 3, "0");
                  case "Z":
                    return i3;
                }
                return null;
              })(t3) || i3.replace(":", "");
            }));
          }, m2.utcOffset = function() {
            return 15 * -Math.round(this.$d.getTimezoneOffset() / 15);
          }, m2.diff = function(r2, d2, l2) {
            var $2, y2 = this, M3 = b.p(d2), m3 = O(r2), v2 = (m3.utcOffset() - this.utcOffset()) * e, g2 = this - m3, D2 = function() {
              return b.m(y2, m3);
            };
            switch (M3) {
              case h:
                $2 = D2() / 12;
                break;
              case c:
                $2 = D2();
                break;
              case f:
                $2 = D2() / 3;
                break;
              case o:
                $2 = (g2 - v2) / 6048e5;
                break;
              case a:
                $2 = (g2 - v2) / 864e5;
                break;
              case u:
                $2 = g2 / n;
                break;
              case s:
                $2 = g2 / e;
                break;
              case i2:
                $2 = g2 / t;
                break;
              default:
                $2 = g2;
            }
            return l2 ? $2 : b.a($2);
          }, m2.daysInMonth = function() {
            return this.endOf(c).$D;
          }, m2.$locale = function() {
            return D[this.$L];
          }, m2.locale = function(t2, e2) {
            if (!t2) return this.$L;
            var n2 = this.clone(), r2 = w(t2, e2, true);
            return r2 && (n2.$L = r2), n2;
          }, m2.clone = function() {
            return b.w(this.$d, this);
          }, m2.toDate = function() {
            return new Date(this.valueOf());
          }, m2.toJSON = function() {
            return this.isValid() ? this.toISOString() : null;
          }, m2.toISOString = function() {
            return this.$d.toISOString();
          }, m2.toString = function() {
            return this.$d.toUTCString();
          }, M2;
        })(), k = _.prototype;
        return O.prototype = k, [["$ms", r], ["$s", i2], ["$m", s], ["$H", u], ["$W", a], ["$M", c], ["$y", h], ["$D", d]].forEach((function(t2) {
          k[t2[1]] = function(e2) {
            return this.$g(e2, t2[0], t2[1]);
          };
        })), O.extend = function(t2, e2) {
          return t2.$i || (t2(e2, _, O), t2.$i = true), O;
        }, O.locale = w, O.isDayjs = S, O.unix = function(t2) {
          return O(1e3 * t2);
        }, O.en = D[g], O.Ls = D, O.p = {}, O;
      }));
    })(dayjs_min$1);
    return dayjs_min$1.exports;
  }
  var dayjs_minExports = requireDayjs_min();
  const dayjs = /* @__PURE__ */ getDefaultExportFromCjs$1(dayjs_minExports);
  var relativeTime$2 = { exports: {} };
  var relativeTime$1 = relativeTime$2.exports;
  var hasRequiredRelativeTime;
  function requireRelativeTime() {
    if (hasRequiredRelativeTime) return relativeTime$2.exports;
    hasRequiredRelativeTime = 1;
    (function(module2, exports$12) {
      !(function(r, e) {
        module2.exports = e();
      })(relativeTime$1, (function() {
        return function(r, e, t) {
          r = r || {};
          var n = e.prototype, o = { future: "in %s", past: "%s ago", s: "a few seconds", m: "a minute", mm: "%d minutes", h: "an hour", hh: "%d hours", d: "a day", dd: "%d days", M: "a month", MM: "%d months", y: "a year", yy: "%d years" };
          function i2(r2, e2, t2, o2) {
            return n.fromToBase(r2, e2, t2, o2);
          }
          t.en.relativeTime = o, n.fromToBase = function(e2, n2, i3, d2, u) {
            for (var f, a, s, l = i3.$locale().relativeTime || o, h = r.thresholds || [{ l: "s", r: 44, d: "second" }, { l: "m", r: 89 }, { l: "mm", r: 44, d: "minute" }, { l: "h", r: 89 }, { l: "hh", r: 21, d: "hour" }, { l: "d", r: 35 }, { l: "dd", r: 25, d: "day" }, { l: "M", r: 45 }, { l: "MM", r: 10, d: "month" }, { l: "y", r: 17 }, { l: "yy", d: "year" }], m = h.length, c = 0; c < m; c += 1) {
              var y = h[c];
              y.d && (f = d2 ? t(e2).diff(i3, y.d, true) : i3.diff(e2, y.d, true));
              var p = (r.rounding || Math.round)(Math.abs(f));
              if (s = f > 0, p <= y.r || !y.r) {
                p <= 1 && c > 0 && (y = h[c - 1]);
                var v = l[y.l];
                u && (p = u("" + p)), a = "string" == typeof v ? v.replace("%d", p) : v(p, n2, y.l, s);
                break;
              }
            }
            if (n2) return a;
            var M = s ? l.future : l.past;
            return "function" == typeof M ? M(a) : M.replace("%s", a);
          }, n.to = function(r2, e2) {
            return i2(r2, e2, this, true);
          }, n.from = function(r2, e2) {
            return i2(r2, e2, this);
          };
          var d = function(r2) {
            return r2.$u ? t.utc() : t();
          };
          n.toNow = function(r2) {
            return this.to(d(this), r2);
          }, n.fromNow = function(r2) {
            return this.from(d(this), r2);
          };
        };
      }));
    })(relativeTime$2);
    return relativeTime$2.exports;
  }
  var relativeTimeExports = requireRelativeTime();
  const relativeTime = /* @__PURE__ */ getDefaultExportFromCjs$1(relativeTimeExports);
  var zhCn$1 = { exports: {} };
  var zhCn = zhCn$1.exports;
  var hasRequiredZhCn;
  function requireZhCn() {
    if (hasRequiredZhCn) return zhCn$1.exports;
    hasRequiredZhCn = 1;
    (function(module2, exports$12) {
      !(function(e, _) {
        module2.exports = _(requireDayjs_min());
      })(zhCn, (function(e) {
        function _(e2) {
          return e2 && "object" == typeof e2 && "default" in e2 ? e2 : { default: e2 };
        }
        var t = _(e), d = { name: "zh-cn", weekdays: "星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"), weekdaysShort: "周日_周一_周二_周三_周四_周五_周六".split("_"), weekdaysMin: "日_一_二_三_四_五_六".split("_"), months: "一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"), monthsShort: "1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"), ordinal: function(e2, _2) {
          return "W" === _2 ? e2 + "周" : e2 + "日";
        }, weekStart: 1, yearStart: 4, formats: { LT: "HH:mm", LTS: "HH:mm:ss", L: "YYYY/MM/DD", LL: "YYYY年M月D日", LLL: "YYYY年M月D日Ah点mm分", LLLL: "YYYY年M月D日ddddAh点mm分", l: "YYYY/M/D", ll: "YYYY年M月D日", lll: "YYYY年M月D日 HH:mm", llll: "YYYY年M月D日dddd HH:mm" }, relativeTime: { future: "%s内", past: "%s前", s: "几秒", m: "1 分钟", mm: "%d 分钟", h: "1 小时", hh: "%d 小时", d: "1 天", dd: "%d 天", M: "1 个月", MM: "%d 个月", y: "1 年", yy: "%d 年" }, meridiem: function(e2, _2) {
          var t2 = 100 * e2 + _2;
          return t2 < 600 ? "凌晨" : t2 < 900 ? "早上" : t2 < 1100 ? "上午" : t2 < 1300 ? "中午" : t2 < 1800 ? "下午" : "晚上";
        } };
        return t.default.locale(d, null, true), d;
      }));
    })(zhCn$1);
    return zhCn$1.exports;
  }
  requireZhCn();
  dayjs.extend(relativeTime);
  dayjs.locale("zh-cn");
  const __vite_import_meta_env__ = { "BASE_URL": "/", "BROWSER": "chrome", "CHROME": true, "COMMAND": "build", "DEV": false, "EDGE": false, "ENTRYPOINT": "background", "FIREFOX": false, "MANIFEST_VERSION": 3, "MODE": "production", "OPERA": false, "PROD": true, "SAFARI": false, "SSR": false, "VITE_API_BASE_URL": "https://datasaver.deepminingai.com/api", "VITE_API_BASE_URL_V1": "https://datasaver.deepminingai.com/api", "VITE_CHROME_EXTENSION_KEY": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz6mSqF9xmKhi3zThuAi5f/Kf+U0C9GWHfEJuf7M57pQ+ybkNiAX2M+XI5UdiFhw8d7Wpmk2rQ72bKGiZDgyV47qe9ntEAO+kF/mPWuoEfhFpvRsb+MzOwiCzLgCHo2FGfeVq+Y38fk/vEi21OSm+MHdKy03ud3a0X9C5c+5ser23e8RKXf5Y2ZrYTPn3kgex+GyhfaKceYDxkq/CkDTnVwUnoDAfm9vhoaJZ4GqQ69rSasOSm4WjdKiIWJbhDZl96ECl/FdUkHnO56rQCkWqSF3Fb9XqJuIz9lHo6PHp44LCNE2hOv7C9UjQpMjVtNx2ynM/sUEJHhOUzhixPdVtKQIDAQAB", "VITE_CHROME_EXTENSION_KEY_POPUP": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3xXBvP+mtfJ1giQcRAco9aEFz8FNwceqOVj9EQkv9It6PoMlnNrpWz1RhzpeXpaFiBbM9Exs+QFL0BQIivzbSkIe/kziMFJdhCryiA5pZZAQSfEKpF8lpleh9BNX2U6HRnwb6s8RGQ9/inrvTAzuZeRIXeHD2/tpGOJV3MLjzPnntcEKTP8A1SfOkHtFS1YOB5jPd/9OR/kpCFL1kpREO/rGvHChIhR3jL0s96KYesyse4ItDRWuAHeNYj1eyCoRjVeSBqm3Ma2uN75xxPED7p/FHej4OaNF0VAiH+z8RRguQl+qFAIEH0NCs5T/eVu9n4dIhesKUZYdpRRJxRo/zwIDAQAB", "VITE_DM_URL": "https://v1.deepminer.ai", "VITE_IMAGE_TYPE": "base64" };
  const DEFAULT_API_BASE_URL = "https://datasaver.deepminingai.com/api";
  function getApiBaseUrl(version2) {
    return __async(this, null, function* () {
      try {
        if (version2) {
          return (__vite_import_meta_env__ == null ? void 0 : __vite_import_meta_env__[`VITE_API_BASE_URL_${String(version2).toUpperCase()}`]) || DEFAULT_API_BASE_URL;
        }
        return DEFAULT_API_BASE_URL;
      } catch (error2) {
        console.error("Failed to get API base URL:", error2);
        return DEFAULT_API_BASE_URL;
      }
    });
  }
  function isExtensionEnv() {
    var _a3;
    return typeof chrome !== "undefined" && !!((_a3 = chrome.runtime) == null ? void 0 : _a3.id);
  }
  function isWebEnv() {
    return !isExtensionEnv();
  }
  let ApiError$1 = class ApiError extends Error {
    constructor(message, isHttpError = false, statusCode) {
      super(message);
      this.isHttpError = isHttpError;
      this.statusCode = statusCode;
      this.name = "ApiError";
    }
  };
  function getDeviceId() {
    return __async(this, null, function* () {
      var _a3;
      try {
        if (isWebEnv()) return "";
        const storage = yield chrome.storage.local.get(["deviceId", "device_config"]);
        return storage.deviceId || ((_a3 = storage.device_config) == null ? void 0 : _a3.deviceId) || "";
      } catch (error2) {
        console.error("获取设备ID失败:", error2);
        return "";
      }
    });
  }
  function displayErrorToast$1(message) {
    toast.error(message, {
      duration: 3e3,
      position: "top-center"
    });
  }
  function validateAuth$1(requireAuth) {
    return __async(this, null, function* () {
      if (isWebEnv()) return null;
      if (!requireAuth) return null;
      const { accessToken } = yield chrome.storage.local.get("accessToken");
      return accessToken || null;
    });
  }
  function parseVersionFromUrl$1(url2) {
    const segments = url2.split("/").filter(Boolean);
    const firstSegment = segments[0];
    return firstSegment && /^v\d+$/.test(firstSegment) ? firstSegment : "";
  }
  function buildRequestHeaders$1(customHeaders, accessToken, hasBody, method) {
    return __async(this, null, function* () {
      var _a3;
      const headers = __spreadValues({}, customHeaders);
      if (hasBody && method !== "GET" && !headers["Content-Type"]) {
        headers["Content-Type"] = "application/json";
      }
      if (accessToken) {
        headers.Authorization = `Bearer ${accessToken}`;
      }
      if (isExtensionEnv()) {
        const storage = yield chrome.storage.local.get(["userInfo", "region_base_url"]);
        const activeSpace = (_a3 = storage.userInfo) == null ? void 0 : _a3.active_space;
        if ((activeSpace == null ? void 0 : activeSpace.id) && (activeSpace == null ? void 0 : activeSpace.space_name)) {
          const spaceMetadata = {
            id: activeSpace.id,
            name: activeSpace.space_name,
            subject_id: activeSpace.subject_id,
            feature_key: activeSpace.feature_key
          };
          const encodedMetadata = encodeSpaceMetadata(spaceMetadata);
          if (encodedMetadata) {
            headers["X-Space-Metadata"] = encodedMetadata;
          }
        }
        if (storage.region_base_url) {
          headers["x-region-url"] = storage.region_base_url;
        }
        const extensionVersion = getExtensionVersion();
        if (extensionVersion) {
          headers["X-Extension-Version"] = extensionVersion;
        }
      }
      return headers;
    });
  }
  function buildRequestConfig$1(method, headers, body, signal) {
    const config2 = {
      method,
      headers
    };
    if (body && method !== "GET") {
      config2.body = typeof body === "string" ? body : JSON.stringify(body);
    }
    if (signal) {
      config2.signal = signal;
    }
    return config2;
  }
  function handleHttpError$1(response, showToast) {
    return __async(this, null, function* () {
      var _a3, _b2, _c2;
      let errorMessage = `HTTP ${response.status}: ${response.statusText}`;
      try {
        const errorData = yield response.json();
        if (response.status === 429 && ((_b2 = (_a3 = errorData.error) == null ? void 0 : _a3.details) == null ? void 0 : _b2.retry_after)) {
          const retryAfter = errorData.error.details.retry_after;
          errorMessage = `操作过于频繁，请${retryAfter}秒后重试`;
        } else {
          errorMessage = ((_c2 = errorData.error) == null ? void 0 : _c2.message) || errorData.error || errorData.message || errorMessage;
        }
      } catch (e) {
      }
      if (showToast) {
        displayErrorToast$1(errorMessage);
      }
      throw new ApiError$1(errorMessage, true, response.status);
    });
  }
  function validateResponseStatus$1(response, showToast) {
    return __async(this, null, function* () {
      var _a3;
      const contentType = response.headers.get("content-type");
      if (!(contentType == null ? void 0 : contentType.includes("application/json"))) {
        return;
      }
      try {
        const clonedResponse = response.clone();
        const responseData = yield clonedResponse.json();
        if (responseData && typeof responseData.status_code === "number" && responseData.status_code !== 200) {
          const errorMessage = responseData.message || `请求失败，状态码: ${responseData.status_code}`;
          if (showToast) {
            displayErrorToast$1(errorMessage);
          }
          throw new ApiError$1(errorMessage, true, responseData.status_code);
        }
        if (responseData && responseData.success === false) {
          const errorMessage = responseData.message || ((_a3 = responseData.data) == null ? void 0 : _a3.error) || "操作失败，请稍后重试";
          if (showToast) {
            displayErrorToast$1(errorMessage);
          }
          throw new ApiError$1(errorMessage, true, response.status);
        }
      } catch (error2) {
        if (error2 instanceof ApiError$1) {
          throw error2;
        }
      }
    });
  }
  function apiRequest$1(_0) {
    return __async(this, arguments, function* (url2, options = {}) {
      const {
        method = "GET",
        headers = {},
        body,
        requireAuth = true,
        showErrorToast = true,
        signal
      } = options;
      try {
        const accessToken = yield validateAuth$1(requireAuth);
        if (requireAuth && !accessToken) {
          return void 0;
        }
        const version2 = parseVersionFromUrl$1(url2);
        const baseUrl = yield getApiBaseUrl(version2);
        const fullUrl = url2.startsWith("http") ? url2 : `${baseUrl}${url2}`;
        const requestHeaders = yield buildRequestHeaders$1(headers, accessToken, !!body, method);
        const requestConfig = buildRequestConfig$1(method, requestHeaders, body, signal);
        const response = yield fetch(fullUrl, requestConfig);
        if (!response.ok) {
          yield handleHttpError$1(response, showErrorToast);
        }
        yield validateResponseStatus$1(response, showErrorToast);
        return response;
      } catch (error2) {
        console.error(`API请求失败 [${method} ${url2}]:`, error2);
        if (error2 instanceof ApiError$1 && error2.isHttpError) {
          throw error2;
        }
        const errorMessage = error2 instanceof Error ? error2.message : "网络连接失败，请检查网络设置";
        if (showErrorToast) {
          displayErrorToast$1(errorMessage);
        }
        throw new Error(errorMessage);
      }
    });
  }
  class ApiError extends Error {
    constructor(message, isHttpError = false, statusCode) {
      super(message);
      this.isHttpError = isHttpError;
      this.statusCode = statusCode;
      this.name = "ApiError";
    }
  }
  function displayErrorToast(message) {
    toast.error(message, {
      duration: 3e3,
      position: "top-center"
    });
  }
  function validateAuth(requireAuth) {
    return __async(this, null, function* () {
      if (!requireAuth) return null;
      const { accessToken } = yield chrome.storage.local.get("accessToken");
      return accessToken || null;
    });
  }
  function parseVersionFromUrl(url2) {
    const segments = url2.split("/").filter(Boolean);
    const firstSegment = segments[0];
    return firstSegment && /^v\d+$/.test(firstSegment) ? firstSegment : "";
  }
  function getCommonHeaders() {
    return __async(this, null, function* () {
      var _a3, _b2;
      const storage = yield chrome.storage.local.get(["userInfo", "refreshToken", "region_base_url"]);
      const accessToken = (_a3 = storage.userInfo) == null ? void 0 : _a3.access_token;
      const activeSpace = (_b2 = storage.userInfo) == null ? void 0 : _b2.active_space;
      const spaceMetadata = (activeSpace == null ? void 0 : activeSpace.id) && (activeSpace == null ? void 0 : activeSpace.space_name) ? {
        id: activeSpace.id,
        name: activeSpace.space_name,
        subject_id: activeSpace.subject_id,
        feature_key: activeSpace.feature_key
      } : null;
      const encodedSpaceMetadata = encodeSpaceMetadata(spaceMetadata);
      const refreshToken = storage.refreshToken;
      const regionBaseUrl = storage.region_base_url;
      const extensionVersion = getExtensionVersion$1();
      return __spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({}, accessToken && { Authorization: `Bearer ${accessToken}` }), encodedSpaceMetadata && { "X-Space-Metadata": encodedSpaceMetadata }), refreshToken && { "X-Refresh-Token": refreshToken }), regionBaseUrl && { "x-region-url": regionBaseUrl }), extensionVersion && { "X-Extension-Version": extensionVersion });
    });
  }
  function buildRequestHeaders(customHeaders, accessToken, hasBody, method) {
    return __async(this, null, function* () {
      var _a3;
      const headers = __spreadValues({}, customHeaders);
      if (hasBody && method !== "GET" && !headers["Content-Type"]) {
        headers["Content-Type"] = "application/json";
      }
      if (accessToken) {
        headers.Authorization = `Bearer ${accessToken}`;
      }
      const storage = yield chrome.storage.local.get(["userInfo", "refreshToken", "region_base_url"]);
      const activeSpace = (_a3 = storage.userInfo) == null ? void 0 : _a3.active_space;
      if ((activeSpace == null ? void 0 : activeSpace.id) && (activeSpace == null ? void 0 : activeSpace.space_name)) {
        const spaceMetadata = {
          id: activeSpace.id,
          name: activeSpace.space_name,
          subject_id: activeSpace.subject_id,
          feature_key: activeSpace.feature_key
        };
        const encodedMetadata = encodeSpaceMetadata(spaceMetadata);
        if (encodedMetadata) {
          headers["X-Space-Metadata"] = encodedMetadata;
        }
      }
      if (storage.refreshToken) {
        headers["X-Refresh-Token"] = storage.refreshToken;
      }
      if (storage.region_base_url) {
        headers["x-region-url"] = storage.region_base_url;
      }
      const extensionVersion = getExtensionVersion$1();
      if (extensionVersion) {
        headers["X-Extension-Version"] = extensionVersion;
      }
      return headers;
    });
  }
  function buildRequestConfig(method, headers, body) {
    const config2 = {
      method,
      headers
    };
    if (body && method !== "GET") {
      config2.body = typeof body === "string" ? body : JSON.stringify(body);
    }
    return config2;
  }
  function handleHttpError(response, showToast) {
    return __async(this, null, function* () {
      var _a3, _b2, _c2;
      let errorMessage = `HTTP ${response.status}: ${response.statusText}`;
      try {
        const errorData = yield response.json();
        if (response.status === 429 && ((_b2 = (_a3 = errorData.error) == null ? void 0 : _a3.details) == null ? void 0 : _b2.retry_after)) {
          const retryAfter = errorData.error.details.retry_after;
          errorMessage = `操作过于频繁，请${retryAfter}秒后重试`;
        } else {
          errorMessage = ((_c2 = errorData.error) == null ? void 0 : _c2.message) || errorData.error || errorData.message || errorMessage;
        }
      } catch (e) {
      }
      if (showToast) {
        displayErrorToast(errorMessage);
      }
      throw new ApiError(errorMessage, true, response.status);
    });
  }
  function validateResponseStatus(response, showToast) {
    return __async(this, null, function* () {
      var _a3;
      const contentType = response.headers.get("content-type");
      if (!(contentType == null ? void 0 : contentType.includes("application/json"))) {
        return;
      }
      try {
        const clonedResponse = response.clone();
        const responseData = yield clonedResponse.json();
        if (responseData && typeof responseData.status_code === "number" && responseData.status_code !== 200) {
          const errorMessage = responseData.message || `请求失败，状态码: ${responseData.status_code}`;
          if (showToast) {
            displayErrorToast(errorMessage);
          }
          throw new ApiError(errorMessage, true, responseData.status_code);
        }
        if (responseData && responseData.success === false) {
          const errorMessage = responseData.message || ((_a3 = responseData.data) == null ? void 0 : _a3.error) || "操作失败，请稍后重试";
          if (showToast) {
            displayErrorToast(errorMessage);
          }
          throw new ApiError(errorMessage, true, response.status);
        }
      } catch (error2) {
        if (error2 instanceof ApiError) {
          throw error2;
        }
      }
    });
  }
  function apiRequest(_0) {
    return __async(this, arguments, function* (url2, options = {}) {
      const { method = "GET", headers = {}, body, requireAuth = true, showErrorToast = true } = options;
      try {
        const accessToken = yield validateAuth(requireAuth);
        if (requireAuth && !accessToken) {
          return void 0;
        }
        const version2 = parseVersionFromUrl(url2);
        const baseUrl = yield getApiBaseUrl$1(version2);
        const fullUrl = url2.startsWith("http") ? url2 : `${baseUrl}${url2}`;
        const requestHeaders = yield buildRequestHeaders(headers, accessToken, !!body, method);
        const requestConfig = buildRequestConfig(method, requestHeaders, body);
        const response = yield fetch(fullUrl, requestConfig);
        if (!response.ok) {
          yield handleHttpError(response, showErrorToast);
        }
        yield validateResponseStatus(response, showErrorToast);
        return response;
      } catch (error2) {
        console.error(`API请求失败 [${method} ${url2}]:`, error2);
        if (error2 instanceof ApiError && error2.isHttpError) {
          throw error2;
        }
        const errorMessage = error2 instanceof Error ? error2.message : "网络连接失败，请检查网络设置";
        if (showErrorToast) {
          displayErrorToast(errorMessage);
        }
        throw new Error(errorMessage);
      }
    });
  }
  function getUploadSignUrlPost$1(request) {
    return __async(this, null, function* () {
      const response = yield apiRequest("/v1/files/upload-sign-url", {
        method: "POST",
        requireAuth: true,
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify(request),
        showErrorToast: false
        // 不自动显示错误toast，由调用方处理
      });
      const data = yield response == null ? void 0 : response.json();
      if (!data.data || !data.data.uploadUrl) {
        throw new Error("API 返回的预签名URL信息不完整");
      }
      return data;
    });
  }
  function uploadFileToSignedUrl$1(file2, uploadUrl, options) {
    return __async(this, null, function* () {
      try {
        const controller = new AbortController();
        const timeoutId = setTimeout(
          () => {
            controller.abort();
          },
          5 * 60 * 1e3
        );
        const headers = {
          "Content-Type": file2.type || "application/octet-stream"
        };
        if (options == null ? void 0 : options.filename) {
          headers["x-oss-meta-filename"] = options.filename;
        }
        if (options == null ? void 0 : options.sourceUrl) {
          headers["x-oss-meta-source-url"] = options.sourceUrl;
        }
        const response = yield fetch(uploadUrl, {
          method: "PUT",
          headers,
          body: file2,
          signal: controller.signal
        });
        clearTimeout(timeoutId);
        if (!response.ok) {
          throw new Error(`上传失败: HTTP ${response.status} ${response.statusText}`);
        }
      } catch (error2) {
        if (error2 instanceof Error) {
          if (error2.name === "AbortError") {
            throw new Error("上传超时");
          }
          throw new Error(`上传过程中发生错误: ${error2.message}`);
        }
        throw new Error("上传过程中发生未知错误");
      }
    });
  }
  function uploadFile$1(file2, options) {
    return __async(this, null, function* () {
      var _a3;
      try {
        const _filename = (options == null ? void 0 : options.filename) || file2.name;
        const contentType = file2.type || "application/octet-stream";
        const signUrlResponse = yield getUploadSignUrlPost$1({
          filename: encodeURIComponent(_filename),
          purpose: options == null ? void 0 : options.purpose,
          contentType
          // metadata: {
          //   sourceUrl: encodeURIComponent(options?.sourceUrl || ''),
          // },
        });
        if (!signUrlResponse.success) {
          return {
            success: false,
            error: signUrlResponse.message || "获取预签名URL失败"
          };
        }
        yield uploadFileToSignedUrl$1(file2, signUrlResponse.data.uploadUrl, __spreadProps(__spreadValues({}, options), {
          filename: encodeURIComponent(_filename)
        }));
        return {
          success: true,
          objectKey: signUrlResponse.data.objectKey,
          // OSS 对象键，用于消息传递
          url: (_a3 = signUrlResponse.data.uploadUrl) == null ? void 0 : _a3.split("?")[0]
          // 完整访问URL（保留用于兼容）
        };
      } catch (error2) {
        return {
          success: false,
          error: error2 instanceof Error ? error2.message : "上传失败"
        };
      }
    });
  }
  function uploadFileFromUrl(fileUrl, filename) {
    return __async(this, null, function* () {
      try {
        const response = yield fetch(fileUrl);
        if (!response.ok) {
          throw new Error(`下载文件失败: HTTP ${response.status}`);
        }
        const blob = yield response.blob();
        const file2 = new File([blob], filename, {
          type: blob.type || "application/octet-stream"
        });
        return yield uploadFile$1(file2);
      } catch (error2) {
        return {
          success: false,
          error: error2 instanceof Error ? error2.message : "从URL上传文件失败"
        };
      }
    });
  }
  class ScreenshotWithHighlightsTool extends BaseBrowserToolExecutor {
    constructor() {
      super(...arguments);
      __publicField2(this, "name", TOOL_NAMES.BROWSER.SCREENSHOT_WITH_HIGHLIGHTS);
    }
    execute(args) {
      return __async(this, null, function* () {
        var _a3, _b2, _c2, _d2;
        const { name: name2 = "highlights", selector, highlightDelay = 500, tabId } = args;
        try {
          const targetTab = tabId ? yield chrome.tabs.get(tabId) : (yield chrome.tabs.query({ active: true, currentWindow: true }))[0];
          if (!targetTab || !targetTab.id) {
            return createErrorResponse("No active tab found or invalid tab ID");
          }
          const tab = targetTab;
          const activeTabId = tab.id;
          if (((_a3 = tab.url) == null ? void 0 : _a3.startsWith("chrome://")) || ((_b2 = tab.url) == null ? void 0 : _b2.startsWith("edge://")) || ((_c2 = tab.url) == null ? void 0 : _c2.startsWith("https://chrome.google.com/webstore")) || ((_d2 = tab.url) == null ? void 0 : _d2.startsWith("https://microsoftedge.microsoft.com/"))) {
            return createErrorResponse(
              "Cannot capture special browser pages or web store pages due to security restrictions."
            );
          }
          yield this.injectContentScript(activeTabId, ["inject-scripts/highlight-injector.js"]);
          yield new Promise((resolve2) => setTimeout(resolve2, 100));
          const highlightResult = yield this.sendMessageToTab(activeTabId, {
            action: "HIGHLIGHT_ELEMENTS",
            selector: selector || null
          });
          if (!highlightResult || !highlightResult.success) {
            return createErrorResponse("Failed to highlight elements");
          }
          const highlightedElements = highlightResult.highlightedElements || [];
          const elementsCount = highlightedElements.length;
          if (elementsCount === 0) {
            yield this.sendMessageToTab(activeTabId, { action: "REMOVE_HIGHLIGHTS" });
            return createErrorResponse("No interactive elements found on the page");
          }
          yield new Promise((resolve2) => setTimeout(resolve2, highlightDelay));
          const screenshotDataUrl = yield chrome.tabs.captureVisibleTab(tab.windowId, {
            format: "png"
          });
          if (!screenshotDataUrl) {
            throw new Error("Failed to capture screenshot");
          }
          const compressed = yield compressImage(screenshotDataUrl, {
            scale: 0.8,
            quality: 0.85,
            format: "image/webp"
          });
          const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").substring(0, 19);
          const screenshotFilename = `${name2}_${timestamp}_screenshot.webp`;
          const screenshotUpload = yield uploadFileFromUrl(compressed.dataUrl, screenshotFilename);
          if (!screenshotUpload.success || !screenshotUpload.url) {
            throw new Error(screenshotUpload.error || "Failed to upload screenshot");
          }
          const jsonData = {
            metadata: {
              url: tab.url || "",
              title: tab.title || "",
              timestamp: (/* @__PURE__ */ new Date()).toISOString(),
              screenshotUrl: screenshotUpload.url,
              selector
            },
            // highlightedElements 已经包含完整的元素详细信息，直接使用
            elements: highlightedElements
          };
          const jsonFilename = `${name2}_${timestamp}_highlights.json`;
          const jsonBlob = new Blob([JSON.stringify(jsonData, null, 2)], {
            type: "application/json"
          });
          const jsonFile = new File([jsonBlob], jsonFilename, { type: "application/json" });
          const jsonUpload = yield uploadFile$1(jsonFile);
          if (!jsonUpload.success || !jsonUpload.url) {
            throw new Error(jsonUpload.error || "Failed to upload JSON data");
          }
          try {
            yield this.sendMessageToTab(activeTabId, { action: "REMOVE_HIGHLIGHTS" });
          } catch (err) {
            console.warn("Failed to remove highlights:", err);
          }
          return {
            content: [
              {
                type: "text",
                text: JSON.stringify({
                  success: true,
                  highlightsJson: jsonUpload.url,
                  screenshot: screenshotUpload.url,
                  count: elementsCount
                })
              }
            ],
            isError: false
          };
        } catch (error2) {
          if (tabId || (yield chrome.tabs.query({ active: true, currentWindow: true }))[0]) {
            try {
              const activeTabId = tabId || (yield chrome.tabs.query({ active: true, currentWindow: true }))[0].id;
              if (activeTabId) {
                yield this.sendMessageToTab(activeTabId, { action: "REMOVE_HIGHLIGHTS" });
              }
            } catch (cleanupErr) {
              console.warn("Failed to cleanup highlights after error:", cleanupErr);
            }
          }
          console.error("Screenshot with highlights error:", error2);
          return createErrorResponse(
            `Failed to capture page with highlights: ${error2.message || String(error2)}`
          );
        }
      });
    }
  }
  const screenshotWithHighlightsTool = new ScreenshotWithHighlightsTool();
  function extractDomain(url2) {
    try {
      const urlObj = new URL(url2);
      return "." + urlObj.hostname.split(".").slice(-2).join(".");
    } catch (e) {
      return "";
    }
  }
  function getCookiesForDomain(domain2) {
    return __async(this, null, function* () {
      var _a3;
      const cookies = yield (_a3 = chrome.cookies) == null ? void 0 : _a3.getAll({ domain: domain2 });
      return cookies.map((c) => `${c.name}=${c.value}`).join("; ");
    });
  }
  function uploadResponseToOSS$1(responseBody, contentType, url2) {
    return __async(this, null, function* () {
      try {
        const urlObj = new URL(url2);
        const domainName = urlObj.hostname.replace(/^www\./, "").replace(/\./g, "_");
        const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").substring(0, 19);
        let extension = "txt";
        let _contentType = "text/plain";
        if (contentType.includes("application/json")) {
          extension = "json";
          _contentType = "application/json";
        } else if (contentType.includes("text/html")) {
          extension = "html";
          _contentType = "text/html";
        } else if (contentType.includes("text/xml") || contentType.includes("application/xml")) {
          extension = "xml";
          _contentType = "text/xml";
        }
        const filename = `fetch_${domainName}_${timestamp}.${extension}`;
        const file2 = new File([responseBody], filename, { type: _contentType });
        const uploadResult = yield uploadFile$1(file2, {
          purpose: "external_resource"
        });
        if (uploadResult.success && uploadResult.url) {
          return uploadResult.url;
        }
        return null;
      } catch (error2) {
        console.error("[Fetch Tool] 上传 OSS 失败:", error2);
        return null;
      }
    });
  }
  const fetchApiToolSchema = {
    url: string$1().describe("The URL to fetch"),
    method: _enum$1(["GET", "POST", "PUT", "DELETE", "PATCH"]).default("GET").describe("HTTP method"),
    headers: record(string$1(), string$1()).optional().describe("Request headers"),
    body: string$1().optional().describe("Request body (for POST/PUT/PATCH)"),
    cookieDomain: string$1().optional().describe('Cookie domain (e.g., ".example.com"). If not specified, extracted from URL'),
    includeCookies: boolean$1().default(true).describe("Whether to include cookies")
  };
  class FetchApiTool extends BaseBrowserToolExecutor {
    constructor() {
      super(...arguments);
      __publicField2(this, "name", "fetch_api");
      __publicField2(this, "description", "Execute HTTP requests in extension background with automatic cookie injection. Large responses are automatically uploaded to OSS to avoid context overflow.");
      __publicField2(this, "annotations", {
        title: "Fetch API",
        category: ToolCategory.NETWORK,
        readOnlyHint: true
      });
      __publicField2(this, "schema", fetchApiToolSchema);
    }
    execute(args) {
      return __async(this, null, function* () {
        const validationResult = this.validateArgs(args);
        if (!validationResult.success) {
          return validationResult.error;
        }
        const {
          url: url2,
          method = "GET",
          headers = {},
          body,
          cookieDomain,
          includeCookies = true
        } = validationResult.data;
        try {
          const requestHeaders = __spreadValues({
            Accept: "application/json, text/plain, */*"
          }, headers);
          if (includeCookies) {
            const domain2 = cookieDomain || extractDomain(url2);
            if (domain2) {
              const cookieHeader = yield getCookiesForDomain(domain2);
              if (cookieHeader) {
                requestHeaders["Cookie"] = cookieHeader;
              }
            }
          }
          try {
            const urlObj = new URL(url2);
            const origin = `${urlObj.protocol}//${urlObj.hostname.replace("api.", "app.")}`;
            requestHeaders["Origin"] = requestHeaders["Origin"] || origin;
            requestHeaders["Referer"] = requestHeaders["Referer"] || `${origin}/`;
          } catch (e) {
          }
          const fetchResponse = yield fetch(url2, {
            method,
            headers: requestHeaders,
            body: body || void 0
          });
          const responseBody = yield fetchResponse.text();
          const contentType = fetchResponse.headers.get("content-type") || "";
          let responseData;
          try {
            responseData = JSON.parse(responseBody);
          } catch (e) {
            responseData = responseBody;
          }
          const bodySize = new Blob([responseBody]).size;
          const uploadedUrl = yield uploadResponseToOSS$1(responseBody, contentType, url2);
          const hostname2 = new URL(url2).hostname;
          const responseText = `${method} ${hostname2} - Status ${fetchResponse.status}

Full data available at: ${uploadedUrl}`;
          return success$1(responseText, {
            status: fetchResponse.status,
            contentType,
            bodySize,
            uploadedFile: uploadedUrl || void 0
          });
        } catch (err) {
          return error$J(
            `Request failed: ${err instanceof Error ? err.message : String(err)}`,
            "EXECUTION_FAILED",
            { url: url2, method }
          );
        }
      });
    }
  }
  const fetchApiBatchToolSchema = {
    requests: array(
      object({
        url: string$1().describe("The URL to fetch"),
        method: _enum$1(["GET", "POST", "PUT", "DELETE", "PATCH"]).optional().describe("HTTP method"),
        headers: record(string$1(), string$1()).optional().describe("Request headers"),
        body: string$1().optional().describe("Request body")
      })
    ).min(1).describe("Array of request configurations"),
    cookieDomain: string$1().optional().describe("Cookie domain for all requests"),
    delayMs: number$1().default(100).describe("Delay between requests (milliseconds)"),
    uploadBatchResult: boolean$1().default(true).describe("Whether to upload batch results to OSS (recommended)")
  };
  class FetchApiBatchTool extends BaseBrowserToolExecutor {
    constructor() {
      super(...arguments);
      __publicField2(this, "name", "fetch_api_batch");
      __publicField2(this, "description", "Execute multiple HTTP requests in batch with automatic cookie injection. All responses are saved to OSS file.");
      __publicField2(this, "annotations", {
        title: "Batch Fetch API",
        category: ToolCategory.NETWORK,
        readOnlyHint: true
      });
      __publicField2(this, "schema", fetchApiBatchToolSchema);
    }
    execute(args) {
      return __async(this, null, function* () {
        const validationResult = this.validateArgs(args);
        if (!validationResult.success) {
          return validationResult.error;
        }
        const {
          requests,
          cookieDomain,
          delayMs = 100,
          uploadBatchResult = true
        } = validationResult.data;
        let sharedCookies = "";
        if (cookieDomain) {
          sharedCookies = yield getCookiesForDomain(cookieDomain);
        }
        const results = [];
        for (let i2 = 0; i2 < requests.length; i2++) {
          const req = requests[i2];
          const reqStartTime = Date.now();
          try {
            const requestHeaders = __spreadValues({
              Accept: "application/json, text/plain, */*"
            }, req.headers);
            if (sharedCookies) {
              requestHeaders["Cookie"] = sharedCookies;
            } else {
              const domain2 = extractDomain(req.url);
              if (domain2) {
                const domainCookies = yield getCookiesForDomain(domain2);
                if (domainCookies) {
                  requestHeaders["Cookie"] = domainCookies;
                }
              }
            }
            try {
              const urlObj = new URL(req.url);
              const origin = `${urlObj.protocol}//${urlObj.hostname.replace("api.", "app.")}`;
              requestHeaders["Origin"] = requestHeaders["Origin"] || origin;
              requestHeaders["Referer"] = requestHeaders["Referer"] || `${origin}/`;
            } catch (e) {
            }
            const fetchResponse = yield fetch(req.url, {
              method: req.method || "GET",
              headers: requestHeaders,
              body: req.body || void 0
            });
            const responseBody = yield fetchResponse.text();
            let responseData;
            try {
              responseData = JSON.parse(responseBody);
            } catch (e) {
              responseData = responseBody;
            }
            const responseHeaders = {};
            fetchResponse.headers.forEach((value, key) => {
              responseHeaders[key] = value;
            });
            results.push({
              url: req.url,
              method: req.method || "GET",
              // requestHeaders,
              requestBody: req.body || null,
              response: {
                status: fetchResponse.status,
                statusText: fetchResponse.statusText,
                // headers: responseHeaders,
                body: responseData,
                contentType: fetchResponse.headers.get("content-type") || ""
              },
              duration: Date.now() - reqStartTime
            });
          } catch (err) {
            results.push({
              url: req.url,
              method: req.method || "GET",
              requestHeaders: {},
              requestBody: req.body || null,
              response: null,
              error: err instanceof Error ? err.message : String(err),
              duration: Date.now() - reqStartTime
            });
          }
          if (i2 < requests.length - 1 && delayMs > 0) {
            yield new Promise((resolve2) => setTimeout(resolve2, delayMs));
          }
        }
        const successCount = results.filter((r) => r.response !== null).length;
        const failCount = results.length - successCount;
        let uploadedUrl = null;
        if (uploadBatchResult) {
          const batchData = {
            totalRequests: requests.length,
            successCount,
            failCount,
            results,
            timestamp: (/* @__PURE__ */ new Date()).toISOString()
          };
          const batchDataJson = JSON.stringify(batchData, null, 2);
          const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").substring(0, 19);
          const filename = `fetch_batch_${timestamp}.json`;
          try {
            const file2 = new File([batchDataJson], filename, { type: "application/json" });
            const uploadResult = yield uploadFile$1(file2, {
              purpose: "external_resource"
            });
            if (uploadResult.success && uploadResult.url) {
              uploadedUrl = uploadResult.url;
            }
          } catch (err) {
            console.error("[Fetch Batch Tool] 上传失败:", err);
          }
        }
        return success$1(
          `Batch completed: ${successCount}/${requests.length} succeeded.

Full results: ${uploadedUrl}`,
          {
            totalRequests: requests.length,
            successCount,
            failCount,
            uploadedFile: uploadedUrl || void 0
          }
        );
      });
    }
  }
  const fetchApiTool = new FetchApiTool();
  const fetchApiBatchTool = new FetchApiBatchTool();
  const DEFAULT_TIMEOUT = 3e4;
  const MIN_TIMEOUT = 1e3;
  const MAX_TIMEOUT = 3e5;
  const UPLOAD_THRESHOLD = 10 * 1024;
  const ALLOWED_METHODS = ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"];
  const backgroundNetworkRequestSchema = {
    url: string$1().url().describe("URL to send the request to. Must be a valid HTTP or HTTPS URL."),
    method: _enum$1(ALLOWED_METHODS).default("GET").describe(`HTTP method. Allowed values: ${ALLOWED_METHODS.join(", ")}`),
    headers: record(string$1(), string$1()).optional().describe("Request headers as key-value pairs"),
    body: string$1().optional().describe("Request body (for POST/PUT/PATCH requests). Must be a string."),
    timeout: number$1().int().min(MIN_TIMEOUT).max(MAX_TIMEOUT).default(DEFAULT_TIMEOUT).describe(
      `Request timeout in milliseconds. Min: ${MIN_TIMEOUT}, Max: ${MAX_TIMEOUT}, Default: ${DEFAULT_TIMEOUT}`
    ),
    saveResponseToFile: boolean$1().default(true).describe(
      "Whether to save the response to a file (uploaded to cloud storage). Default: false. Recommended for large responses to avoid context overflow. When enabled, the file URL will be returned instead of the full response body."
    )
  };
  function generateOSSFilename(url2, method) {
    try {
      const urlObj = new URL(url2);
      const hostname2 = urlObj.hostname.replace(/\./g, "_");
      const pathname = urlObj.pathname.replace(/\//g, "_") || "_root";
      const timestamp = Date.now();
      const methodLower = method.toLowerCase();
      return `network_request_${methodLower}_${hostname2}${pathname}_${timestamp}.json`;
    } catch (e) {
      return `network_request_${Date.now()}.json`;
    }
  }
  function shouldUploadResponse(bodySize, contentType) {
    if (bodySize >= UPLOAD_THRESHOLD) {
      return true;
    }
    const binaryTypes = [
      "image/",
      "video/",
      "audio/",
      "application/pdf",
      "application/zip",
      "application/octet-stream"
    ];
    return binaryTypes.some((type2) => contentType.includes(type2));
  }
  function uploadResponseToOSS(responseData, filename) {
    return __async(this, null, function* () {
      try {
        console.log("[Background Network Request] 准备上传响应到 OSS, 文件名:", filename);
        const jsonContent = JSON.stringify(responseData, null, 2);
        const file2 = new File([jsonContent], filename, { type: "application/json" });
        const uploadResult = yield uploadFile$1(file2, {
          purpose: "external_resource"
        });
        if (uploadResult.success && uploadResult.url) {
          console.log("[Background Network Request] OSS 上传成功:", uploadResult.url);
          return uploadResult.url;
        }
        console.error("[Background Network Request] OSS 上传失败:", uploadResult.error);
        return null;
      } catch (err) {
        console.error("[Background Network Request] OSS 上传异常:", err);
        return null;
      }
    });
  }
  class BackgroundNetworkRequestTool extends BaseBrowserToolExecutor {
    constructor() {
      super(...arguments);
      __publicField2(this, "name", TOOL_NAMES.BROWSER.BACKGROUND_NETWORK_REQUEST);
      __publicField2(this, "description", "Send HTTP requests in the background context without requiring active tabs or content scripts. Large responses are automatically uploaded to OSS to avoid context overflow. Supports all standard HTTP methods with comprehensive error handling.");
      __publicField2(this, "annotations", {
        title: "Background Network Request",
        category: ToolCategory.NETWORK,
        readOnlyHint: true
      });
      __publicField2(this, "schema", backgroundNetworkRequestSchema);
    }
    execute(args) {
      return __async(this, null, function* () {
        console.log("[Background Network Request] 开始执行，原始参数:", args);
        const validationResult = this.validateArgs(args);
        if (!validationResult.success) {
          return validationResult.error;
        }
        const {
          url: url2,
          method = "GET",
          headers = {},
          body,
          timeout = DEFAULT_TIMEOUT,
          saveResponseToFile = false
        } = validationResult.data;
        if ((method === "GET" || method === "HEAD") && body) {
          return error$J(`${method} requests should not include a request body`, "INVALID_PARAMS", {
            method,
            hasBody: true
          });
        }
        if (url2.startsWith("chrome://") || url2.startsWith("edge://") || url2.startsWith("about:")) {
          return error$J("Browser internal URLs are not supported", "INVALID_URL", { url: url2 });
        }
        try {
          const controller = new AbortController();
          const timeoutId = setTimeout(() => controller.abort(), timeout);
          const startTime = Date.now();
          const requestOptions = {
            method,
            headers,
            signal: controller.signal
          };
          if (headers["x-redirect-control"]) {
            requestOptions.redirect = headers["x-redirect-control"];
          }
          if (body && method !== "GET" && method !== "HEAD") {
            requestOptions.body = body;
            if (!headers["Content-Type"] && !headers["content-type"]) {
              try {
                JSON.parse(body);
                requestOptions.headers = __spreadProps(__spreadValues({}, requestOptions.headers), {
                  "Content-Type": "application/json"
                });
              } catch (e) {
              }
            }
          }
          console.log(`[Background Network Request] 发送请求: ${method} ${url2}`);
          const response = yield fetch(url2, requestOptions);
          clearTimeout(timeoutId);
          const responseText = yield response.text();
          const contentType = response.headers.get("content-type") || "text/plain";
          const bodySize = new Blob([responseText]).size;
          const duration2 = Date.now() - startTime;
          const responseData = {
            success: true,
            status: response.status,
            statusText: response.statusText,
            headers: Object.fromEntries(response.headers.entries()),
            body: responseText,
            url: response.url,
            redirected: response.redirected,
            contentType,
            bodySize
          };
          console.log(
            `[Background Network Request] 响应状态: ${response.status}, 大小: ${bodySize} bytes, 耗时: ${duration2}ms`
          );
          let uploadedUrl = null;
          const shouldUpload = saveResponseToFile && shouldUploadResponse(bodySize, contentType);
          if (shouldUpload) {
            const filename = generateOSSFilename(url2, method);
            uploadedUrl = yield uploadResponseToOSS(responseData, filename);
          }
          const hostname2 = new URL(url2).hostname;
          let message = `${method} ${hostname2} - Status ${response.status}`;
          if (uploadedUrl) {
            message += `

Full response data available at: ${uploadedUrl}`;
          } else {
            message = `${JSON.stringify(responseData, null, 2)}`;
          }
          return success$1(message, {
            status: response.status,
            statusText: response.statusText,
            contentType,
            bodySize,
            duration: duration2,
            redirected: response.redirected,
            uploadedFile: uploadedUrl || void 0
          });
        } catch (err) {
          console.error("[Background Network Request] 请求失败:", err);
          let errorMessage = "未知错误";
          let errorType = "EXECUTION_ERROR";
          if (err.name === "AbortError") {
            errorMessage = `请求超时 (${timeout}ms)`;
            errorType = "TIMEOUT";
          } else if (err instanceof TypeError) {
            errorMessage = `网络错误: ${err.message}`;
            errorType = "NETWORK_ERROR";
          } else if (err.message) {
            errorMessage = err.message;
            errorType = err.name || "ERROR";
          }
          return error$J(errorMessage, errorType, {
            url: url2,
            method,
            timeout,
            stack: err.stack
          });
        }
      });
    }
  }
  const backgroundNetworkRequestTool = new BackgroundNetworkRequestTool();
  const DEBUGGER_PROTOCOL_VERSION$1 = "1.3";
  const HIGHLIGHT_COLORS = {
    // 蓝色（点击）
    RED: { primary: "#ff0000", secondary: "rgba(255, 0, 0, 0.3)" }
  };
  const ELEMENT_CONFIG = {
    button: 'button, input[type="button"], input[type="submit"], [role="button"]',
    link: 'a[href], [role="link"]',
    input: 'input:not([type="button"]):not([type="submit"]):not([type="checkbox"]):not([type="radio"])',
    checkbox: 'input[type="checkbox"], [role="checkbox"]',
    radio: 'input[type="radio"], [role="radio"]',
    textarea: "textarea",
    select: "select",
    tab: '[role="tab"]',
    interactive: '[onclick], [tabindex]:not([tabindex^="-"]), [role="menuitem"], [role="slider"], [role="option"], [role="treeitem"]'
  };
  class CDPDebuggerManager {
    /**
     * 获取目标标签页
     * @param tabId - 可选的标签页 ID，如果不提供则获取当前活动标签页
     * @param activateTab - 是否激活目标标签页（默认：false，后台执行）
     * @returns 目标标签页对象
     * @throws 如果标签页不存在
     */
    getTargetTab(tabId, activateTab = false) {
      return __async(this, null, function* () {
        let targetTab;
        if (tabId) {
          try {
            targetTab = yield chrome.tabs.get(tabId);
          } catch (error2) {
            throw new Error(
              `Tab with ID ${tabId} not found. The tab may have been closed or the ID is invalid. Error: ${error2 instanceof Error ? error2.message : String(error2)}`
            );
          }
          if (activateTab) {
            yield chrome.tabs.update(tabId, { active: true });
            yield chrome.windows.update(targetTab.windowId, { focused: true });
          }
        } else {
          const tabs = yield chrome.tabs.query({ active: true, currentWindow: true });
          targetTab = tabs[0];
        }
        if (!targetTab || !targetTab.id) {
          throw new Error(ERROR_MESSAGES.TAB_NOT_FOUND);
        }
        return targetTab;
      });
    }
    /**
     * 检查调试器是否已被附加
     * @param tabId - 标签页 ID
     * @returns 现有的调试器目标信息（如果已附加）
     */
    checkExistingDebugger(tabId) {
      return __async(this, null, function* () {
        const targets = yield chrome.debugger.getTargets();
        return targets.find((t) => t.tabId === tabId && t.attached && t.type === "page");
      });
    }
    /**
     * 附加调试器到目标标签页
     * 如果已被本扩展附加，则复用现有连接；如果被其他工具附加，则报错
     * @param tabId - 标签页 ID
     * @returns 附加结果，包含是否是新附加的标志
     * @throws 如果调试器已被其他工具（如 DevTools）附加
     */
    attachDebugger(tabId) {
      return __async(this, null, function* () {
        var _a3;
        const existingTarget = yield this.checkExistingDebugger(tabId);
        if (existingTarget) {
          if (existingTarget.extensionId && existingTarget.extensionId === chrome.runtime.id) {
            console.log("[CDP 调试器] 调试器已被本扩展附加，复用现有连接");
            return { attached: false, tabId };
          } else if (!existingTarget.extensionId) {
            console.warn(`[CDP 调试器] 检测到标签页 ${tabId} 已附加但 extensionId 为空，尝试重新附加`);
            try {
              yield this.detachDebugger(tabId);
              yield new Promise((resolve2) => setTimeout(resolve2, 100));
            } catch (error2) {
              console.warn(`[CDP 调试器] 尝试分离失败:`, error2);
            }
          }
        }
        try {
          yield chrome.debugger.attach({ tabId }, DEBUGGER_PROTOCOL_VERSION$1);
          console.log(`[CDP 调试器] 成功附加到标签页 ${tabId}`);
          return { attached: true, tabId };
        } catch (error2) {
          if ((_a3 = error2.message) == null ? void 0 : _a3.includes("Cannot attach to the target with an attached client")) {
            throw new Error(
              `调试器已附加到标签页 ${tabId}，可能是 DevTools 或其他扩展正在使用。请关闭 DevTools 后重试`
            );
          }
          throw error2;
        }
      });
    }
    /**
     * 从标签页分离调试器
     * @param tabId - 标签页 ID
     */
    detachDebugger(tabId) {
      return __async(this, null, function* () {
        try {
          yield chrome.debugger.detach({ tabId });
          console.log(`[CDP 调试器] 成功从标签页 ${tabId} 分离`);
        } catch (error2) {
          console.warn(`[CDP 调试器] 分离调试器失败 (tabId: ${tabId}):`, error2);
        }
      });
    }
    /**
     * 使用调试器执行操作（自动管理附加和分离）
     * @param tabId - 标签页 ID
     * @param callback - 需要执行的操作
     * @returns 操作结果
     */
    withDebugger(tabId, callback) {
      return __async(this, null, function* () {
        const attachResult = yield this.attachDebugger(tabId);
        try {
          return yield callback(tabId);
        } finally {
          if (attachResult.attached) {
            yield this.detachDebugger(tabId);
          }
        }
      });
    }
    /**
     * 发送 CDP 命令
     * @param tabId - 标签页 ID
     * @param method - CDP 方法名
     * @param params - 方法参数
     * @returns CDP 命令响应
     */
    sendCommand(tabId, method, params) {
      return __async(this, null, function* () {
        return yield chrome.debugger.sendCommand({ tabId }, method, params);
      });
    }
  }
  const cdpDebuggerManager = new CDPDebuggerManager();
  const DEBUGGING_ERROR_KEYWORDS = [
    "Debugger is not attached",
    "Target closed",
    "Inspector protocol error",
    "Detached while handling",
    "Cannot access contents of",
    "Target crashed",
    "Debugger session not found",
    "Connection lost"
  ];
  function isDebuggingError(message) {
    const lowerMessage = message.toLowerCase();
    return DEBUGGING_ERROR_KEYWORDS.some((keyword2) => lowerMessage.includes(keyword2.toLowerCase()));
  }
  class CDPError extends Error {
    constructor(message, isDebuggingError2 = false) {
      super(message);
      __publicField2(this, "isDebuggingError");
      this.name = "CDPError";
      this.isDebuggingError = isDebuggingError2;
    }
  }
  function createSession(tabId) {
    return {
      send(method, params) {
        return new Promise((resolve2, reject) => {
          chrome.debugger.sendCommand({ tabId }, method, params, (result2) => {
            if (chrome.runtime.lastError) {
              const errorMessage = chrome.runtime.lastError.message || "Unknown CDP error";
              const isDebugErr = isDebuggingError(errorMessage);
              console.error(
                `[CDP Session] 命令失败 tab=${tabId}, method=${method}, isDebuggingError=${isDebugErr}, error=${errorMessage}`
              );
              reject(new CDPError(errorMessage, isDebugErr));
              return;
            }
            resolve2(result2);
          });
        });
      }
    };
  }
  class CDPSessionPool {
    constructor(config2) {
      __publicField2(this, "sessions", /* @__PURE__ */ new Map());
      __publicField2(this, "config");
      this.config = __spreadValues({
        inactivityTimeout: 60 * 1e3,
        // 60秒
        maxSessions: 50,
        enableDebugLog: false
      }, config2);
      this.setupEventListeners();
    }
    /**
     * 获取或创建会话
     */
    getOrCreateSession(tabId) {
      return __async(this, null, function* () {
        let session = this.sessions.get(tabId);
        if (session) {
          session.lastUsed = Date.now();
          session.useCount++;
          this.refreshCleanupTimer(tabId, session);
          this.log(`[会话池] 复用会话 tab=${tabId}, 使用次数=${session.useCount}`);
          return session;
        }
        if (this.sessions.size >= this.config.maxSessions) {
          yield this.evictOldestSession();
        }
        this.log(`[会话池] 创建新会话 tab=${tabId}`);
        yield cdpDebuggerManager.attachDebugger(tabId);
        const cdpSession = createSession(tabId);
        yield cdpSession.send("Page.enable");
        const viewport = yield this.initViewport(cdpSession);
        session = {
          target: { tabId },
          session: cdpSession,
          viewport,
          lastUsed: Date.now(),
          createdAt: Date.now(),
          useCount: 1
        };
        this.sessions.set(tabId, session);
        this.refreshCleanupTimer(tabId, session);
        return session;
      });
    }
    /**
     * 移除会话
     */
    removeSession(tabId) {
      return __async(this, null, function* () {
        const session = this.sessions.get(tabId);
        if (!session) return;
        if (session.detachTimer) {
          clearTimeout(session.detachTimer);
        }
        try {
          yield cdpDebuggerManager.detachDebugger(tabId);
        } catch (error2) {
          this.log(`[会话池] 分离调试器失败 tab=${tabId}:`, error2);
        }
        this.sessions.delete(tabId);
        this.log(`[会话池] 移除会话 tab=${tabId}, 使用次数=${session.useCount}`);
      });
    }
    /**
     * 清理所有会话
     */
    cleanupAll() {
      return __async(this, null, function* () {
        const tabIds = Array.from(this.sessions.keys());
        yield Promise.all(tabIds.map((tabId) => this.removeSession(tabId)));
      });
    }
    /**
     * 获取会话统计信息
     */
    getStats() {
      return {
        totalSessions: this.sessions.size,
        sessions: Array.from(this.sessions.entries()).map(([tabId, info]) => ({
          tabId,
          useCount: info.useCount,
          age: Date.now() - info.createdAt,
          idle: Date.now() - info.lastUsed
        }))
      };
    }
    /**
     * 刷新清理定时器
     */
    refreshCleanupTimer(tabId, session) {
      if (session.detachTimer) {
        clearTimeout(session.detachTimer);
      }
      session.detachTimer = setTimeout(() => __async(this, null, function* () {
        this.log(`[会话池] 超时清理 tab=${tabId}`);
        yield this.removeSession(tabId);
      }), this.config.inactivityTimeout);
    }
    /**
     * 驱逐最旧的会话
     */
    evictOldestSession() {
      return __async(this, null, function* () {
        let oldestTabId = null;
        let oldestTime = Infinity;
        for (const [tabId, session] of this.sessions.entries()) {
          if (session.lastUsed < oldestTime) {
            oldestTime = session.lastUsed;
            oldestTabId = tabId;
          }
        }
        if (oldestTabId !== null) {
          this.log(`[会话池] 驱逐最旧会话 tab=${oldestTabId}`);
          yield this.removeSession(oldestTabId);
        }
      });
    }
    /**
     * 初始化视口信息
     */
    initViewport(session) {
      return __async(this, null, function* () {
        var _a3, _b2;
        try {
          yield session.send("Emulation.clearDeviceMetricsOverride").catch(() => {
          });
          const metrics = yield session.send("Page.getLayoutMetrics");
          return {
            width: ((_a3 = metrics.cssLayoutViewport) == null ? void 0 : _a3.clientWidth) || 1920,
            height: ((_b2 = metrics.cssLayoutViewport) == null ? void 0 : _b2.clientHeight) || 1080
          };
        } catch (error2) {
          try {
            const result2 = yield session.send("Runtime.evaluate", {
              expression: "({ width: window.innerWidth, height: window.innerHeight })",
              returnByValue: true
            });
            return result2.result.value;
          } catch (e) {
            this.log("[会话池] 无法获取视口信息，使用默认值");
            return { width: 1920, height: 1080 };
          }
        }
      });
    }
    /**
     * 设置事件监听器
     */
    setupEventListeners() {
      chrome.tabs.onRemoved.addListener((tabId) => {
        if (this.sessions.has(tabId)) {
          this.log(`[会话池] Tab 已关闭，清理会话 tab=${tabId}`);
          this.removeSession(tabId);
        }
      });
      chrome.debugger.onDetach.addListener((source, reason) => {
        if (source.tabId && this.sessions.has(source.tabId)) {
          this.log(`[会话池] 调试器已分离 tab=${source.tabId}, reason=${reason}`);
          const session = this.sessions.get(source.tabId);
          if (session == null ? void 0 : session.detachTimer) {
            clearTimeout(session.detachTimer);
          }
          this.sessions.delete(source.tabId);
        }
      });
    }
    log(...args) {
      if (this.config.enableDebugLog) {
        console.log(...args);
      }
    }
  }
  const cdpSessionPool = new CDPSessionPool();
  class CDPSessionExecutor {
    constructor(sessionPool, config2) {
      __publicField2(this, "sessionPool");
      __publicField2(this, "config");
      this.sessionPool = sessionPool;
      this.config = __spreadValues({
        maxRetries: 2,
        // 最多重试 2 次（总共 3 次尝试）
        debuggingErrorDelay: 1e3,
        otherErrorDelay: 500
      }, config2);
    }
    /**
     * 使用会话执行操作（带重试）
     * @param tabId - 标签页 ID
     * @param handler - 操作处理器
     * @returns 操作结果
     */
    executeWithSession(tabId, handler) {
      return __async(this, null, function* () {
        let sessionInfo = yield this.sessionPool.getOrCreateSession(tabId);
        let retryCount = 0;
        while (retryCount <= this.config.maxRetries) {
          try {
            const result2 = yield handler(sessionInfo.session, sessionInfo.viewport);
            console.log(`[执行器] 操作成功 tab=${tabId}, 重试次数=${retryCount}`);
            return result2;
          } catch (error2) {
            const isDebuggingErr = error2 instanceof CDPError && error2.isDebuggingError;
            yield this.sessionPool.removeSession(tabId);
            retryCount++;
            if (retryCount > this.config.maxRetries) {
              console.error(`[执行器] 操作失败 tab=${tabId}, 已重试 ${this.config.maxRetries} 次`);
              throw error2;
            }
            const delay = isDebuggingErr ? this.config.debuggingErrorDelay : this.config.otherErrorDelay;
            console.warn(
              `[执行器] 重试 ${retryCount}/${this.config.maxRetries} tab=${tabId}, 等待 ${delay}ms, 错误: ${error2 instanceof Error ? error2.message : String(error2)}`
            );
            yield new Promise((resolve2) => setTimeout(resolve2, delay));
            try {
              sessionInfo = yield this.sessionPool.getOrCreateSession(tabId);
            } catch (createError) {
              console.error(`[执行器] 创建新会话失败 tab=${tabId}:`, createError);
              throw createError;
            }
          }
        }
        throw new Error("Unexpected end of retry loop");
      });
    }
    /**
     * 获取会话池统计信息
     */
    getStats() {
      return this.sessionPool.getStats();
    }
    /**
     * 清理所有会话
     */
    cleanupAll() {
      return __async(this, null, function* () {
        yield this.sessionPool.cleanupAll();
      });
    }
  }
  const cdpSessionExecutor = new CDPSessionExecutor(cdpSessionPool);
  class CDPElementHelper {
    constructor() {
      /**
       * 检查元素是否可见的通用表达式
       */
      __publicField2(this, "VISIBILITY_CHECK", `
    const style = window.getComputedStyle(element);
    const isVisible = style.display !== 'none' && 
                     style.visibility !== 'hidden' && 
                     style.opacity !== '0';
  `);
      /**
       * 获取元素的矩形信息的通用表达式
       */
      __publicField2(this, "GET_RECT", `
    const rect = element.getBoundingClientRect();
  `);
      /**
       * 获取滚动位置的通用表达式
       */
      __publicField2(this, "GET_SCROLL", `
    const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
    const scrollLeft = window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0;
  `);
    }
    /**
     * 通过 CSS 选择器查找元素并获取完整信息
     * @param tabId - 标签页 ID
     * @param selector - CSS 选择器
     * @param options - 可选配置
     * @returns 元素信息，如果未找到或不可见则返回带有 error 字段的对象
     */
    findElement(_0, _1) {
      return __async(this, arguments, function* (tabId, selector, options = {}) {
        var _a3;
        const {
          includeAbsolutePosition = true,
          includeViewport = true,
          includeScroll = true
        } = options;
        const expression = `
      (function() {
        const element = document.querySelector(${JSON.stringify(selector)});
        if (!element) return { error: 'Element not found' };
        
        ${this.VISIBILITY_CHECK}
        
        if (!isVisible) {
          return { error: 'Element is not visible' };
        }
        
        ${this.GET_RECT}
        ${includeScroll ? this.GET_SCROLL : ""}
        
        const result = {
          tagName: element.tagName,
          id: element.id,
          className: element.className,
          text: element.textContent?.trim().substring(0, 100) || '',
          href: element.href || null,
          type: element.type || null,
          isVisible: true,
          rect: {
            x: rect.x,
            y: rect.y,
            width: rect.width,
            height: rect.height,
            top: rect.top,
            right: rect.right,
            bottom: rect.bottom,
            left: rect.left,
          },
        };
        
        ${includeAbsolutePosition && includeScroll ? `
        result.absolutePosition = {
          top: rect.top + scrollTop,
          left: rect.left + scrollLeft,
          right: rect.right + scrollLeft,
          bottom: rect.bottom + scrollTop,
          centerX: rect.left + scrollLeft + rect.width / 2,
          centerY: rect.top + scrollTop + rect.height / 2,
        };
        ` : ""}
        
        ${includeViewport ? `
        result.viewport = {
          width: window.innerWidth,
          height: window.innerHeight,
        };
        ` : ""}
        
        ${includeScroll ? `
        result.currentScroll = {
          x: scrollLeft,
          y: scrollTop,
        };
        ` : ""}
        
        result.centerX = rect.left + rect.width / 2;
        result.centerY = rect.top + rect.height / 2;
        
        return result;
      })()
    `;
        const result2 = yield cdpDebuggerManager.sendCommand(tabId, "Runtime.evaluate", {
          expression,
          returnByValue: true
        });
        return ((_a3 = result2 == null ? void 0 : result2.result) == null ? void 0 : _a3.value) || { error: "Failed to evaluate expression" };
      });
    }
    /**
     * 检查元素是否存在
     * @param tabId - 标签页 ID
     * @param selector - CSS 选择器
     * @returns 元素是否存在
     */
    elementExists(tabId, selector) {
      return __async(this, null, function* () {
        var _a3;
        const expression = `
      (function() {
        const element = document.querySelector(${JSON.stringify(selector)});
        return !!element;
      })()
    `;
        const result2 = yield cdpDebuggerManager.sendCommand(tabId, "Runtime.evaluate", {
          expression,
          returnByValue: true
        });
        return ((_a3 = result2 == null ? void 0 : result2.result) == null ? void 0 : _a3.value) === true;
      });
    }
    /**
     * 检查元素是否可见
     * @param tabId - 标签页 ID
     * @param selector - CSS 选择器
     * @returns 元素是否可见
     */
    isElementVisible(tabId, selector) {
      return __async(this, null, function* () {
        var _a3;
        const expression = `
      (function() {
        const element = document.querySelector(${JSON.stringify(selector)});
        if (!element) return false;
        
        ${this.VISIBILITY_CHECK}
        
        return isVisible;
      })()
    `;
        const result2 = yield cdpDebuggerManager.sendCommand(tabId, "Runtime.evaluate", {
          expression,
          returnByValue: true
        });
        return ((_a3 = result2 == null ? void 0 : result2.result) == null ? void 0 : _a3.value) === true;
      });
    }
    /**
     * 获取元素的矩形信息
     * @param tabId - 标签页 ID
     * @param selector - CSS 选择器
     * @returns 元素矩形信息
     */
    getElementRect(tabId, selector) {
      return __async(this, null, function* () {
        var _a3;
        const expression = `
      (function() {
        const element = document.querySelector(${JSON.stringify(selector)});
        if (!element) return null;
        
        ${this.GET_RECT}
        
        return {
          x: rect.x,
          y: rect.y,
          width: rect.width,
          height: rect.height,
          top: rect.top,
          right: rect.right,
          bottom: rect.bottom,
          left: rect.left,
        };
      })()
    `;
        const result2 = yield cdpDebuggerManager.sendCommand(tabId, "Runtime.evaluate", {
          expression,
          returnByValue: true
        });
        return (_a3 = result2 == null ? void 0 : result2.result) == null ? void 0 : _a3.value;
      });
    }
    /**
     * 获取元素在页面中的绝对位置
     * @param tabId - 标签页 ID
     * @param selector - CSS 选择器
     * @returns 元素绝对位置信息
     */
    getElementAbsolutePosition(tabId, selector) {
      return __async(this, null, function* () {
        var _a3;
        const expression = `
      (function() {
        const element = document.querySelector(${JSON.stringify(selector)});
        if (!element) return null;
        
        ${this.GET_RECT}
        ${this.GET_SCROLL}
        
        return {
          top: rect.top + scrollTop,
          left: rect.left + scrollLeft,
          right: rect.right + scrollLeft,
          bottom: rect.bottom + scrollTop,
          centerX: rect.left + scrollLeft + rect.width / 2,
          centerY: rect.top + scrollTop + rect.height / 2,
        };
      })()
    `;
        const result2 = yield cdpDebuggerManager.sendCommand(tabId, "Runtime.evaluate", {
          expression,
          returnByValue: true
        });
        return (_a3 = result2 == null ? void 0 : result2.result) == null ? void 0 : _a3.value;
      });
    }
    /**
     * 检查元素是否在视口内
     * @param tabId - 标签页 ID
     * @param selector - CSS 选择器
     * @returns 元素是否在视口内
     */
    isElementInViewport(tabId, selector) {
      return __async(this, null, function* () {
        var _a3;
        const expression = `
      (function() {
        const element = document.querySelector(${JSON.stringify(selector)});
        if (!element) return false;
        
        ${this.GET_RECT}
        
        const viewportHeight = window.innerHeight;
        const viewportWidth = window.innerWidth;
        
        return rect.top >= 0 && 
               rect.left >= 0 && 
               rect.bottom <= viewportHeight && 
               rect.right <= viewportWidth;
      })()
    `;
        const result2 = yield cdpDebuggerManager.sendCommand(tabId, "Runtime.evaluate", {
          expression,
          returnByValue: true
        });
        return ((_a3 = result2 == null ? void 0 : result2.result) == null ? void 0 : _a3.value) === true;
      });
    }
    /**
     * 获取视口信息
     * @param tabId - 标签页 ID
     * @returns 视口信息
     */
    getViewportInfo(tabId) {
      return __async(this, null, function* () {
        var _a3;
        const expression = `
      ({
        width: window.innerWidth,
        height: window.innerHeight,
      })
    `;
        const result2 = yield cdpDebuggerManager.sendCommand(tabId, "Runtime.evaluate", {
          expression,
          returnByValue: true
        });
        return ((_a3 = result2 == null ? void 0 : result2.result) == null ? void 0 : _a3.value) || { width: 800, height: 600 };
      });
    }
    /**
     * 获取当前滚动位置
     * @param tabId - 标签页 ID
     * @returns 当前滚动位置
     */
    getCurrentScrollPosition(tabId) {
      return __async(this, null, function* () {
        var _a3;
        const expression = `
      (function() {
        ${this.GET_SCROLL}
        return { x: scrollLeft, y: scrollTop };
      })()
    `;
        const result2 = yield cdpDebuggerManager.sendCommand(tabId, "Runtime.evaluate", {
          expression,
          returnByValue: true
        });
        return ((_a3 = result2 == null ? void 0 : result2.result) == null ? void 0 : _a3.value) || { x: 0, y: 0 };
      });
    }
    /**
     * 获取指定坐标位置的元素
     * @param tabId - 标签页 ID
     * @param x - X 坐标
     * @param y - Y 坐标
     * @returns 元素信息
     */
    getElementAtPoint(tabId, x, y) {
      return __async(this, null, function* () {
        var _a3;
        const expression = `
      (function() {
        const elements = document.elementsFromPoint(${x}, ${y});
        const element = elements.filter(el => el.id !== 'mcp-page-protection-shadow-root')[0];
        
        if (!element) {
          return {
            clickMethod: 'coordinates',
            clickPosition: { x: ${x}, y: ${y} },
            warning: 'No element found at the specified coordinates'
          };
        }
        
        ${this.GET_RECT}
        
        return {
          tagName: element.tagName,
          id: element.id,
          className: element.className,
          text: element.textContent?.trim().substring(0, 100) || '',
          href: element.href || null,
          type: element.type || null,
          isVisible: true,
          rect: {
            x: rect.x,
            y: rect.y,
            width: rect.width,
            height: rect.height,
            top: rect.top,
            right: rect.right,
            bottom: rect.bottom,
            left: rect.left,
          },
          clickMethod: 'coordinates',
          clickPosition: { x: ${x}, y: ${y} }
        };
      })()
    `;
        const result2 = yield cdpDebuggerManager.sendCommand(tabId, "Runtime.evaluate", {
          expression,
          returnByValue: true
        });
        return (_a3 = result2 == null ? void 0 : result2.result) == null ? void 0 : _a3.value;
      });
    }
    /**
     * 聚焦到指定元素
     * @param tabId - 标签页 ID
     * @param selector - CSS 选择器
     * @returns 聚焦结果
     */
    focusElement(tabId, selector) {
      return __async(this, null, function* () {
        var _a3;
        const expression = `
      (function() {
        const element = document.querySelector(${JSON.stringify(selector)});
        if (!element) return { success: false, error: 'Element not found' };

        if (typeof element.focus === 'function') {
          element.focus();
        }

        return {
          success: true,
          tagName: element.tagName,
          id: element.id,
          className: element.className,
          type: element.type || null
        };
      })()
    `;
        const result2 = yield cdpDebuggerManager.sendCommand(tabId, "Runtime.evaluate", {
          expression,
          returnByValue: true
        });
        return ((_a3 = result2 == null ? void 0 : result2.result) == null ? void 0 : _a3.value) || { success: false, error: "Failed to focus element" };
      });
    }
    /**
     * 通过 backendDOMNodeId 获取元素位置信息
     * @param tabId - 标签页 ID
     * @param backendNodeId - 后端节点 ID（来自可访问性树）
     * @returns 元素位置信息
     */
    getElementByBackendNodeId(tabId, backendNodeId) {
      return __async(this, null, function* () {
        try {
          yield cdpDebuggerManager.sendCommand(tabId, "DOM.enable", {});
          try {
            yield cdpDebuggerManager.sendCommand(tabId, "DOM.getDocument", {
              depth: -1,
              // -1 表示获取完整的 DOM 树
              pierce: true
              // 穿透 shadow DOM
            });
            console.log(`[CDP Element Helper] 尝试转换 backendNodeId: ${backendNodeId}`);
            const pushResult = yield cdpDebuggerManager.sendCommand(
              tabId,
              "DOM.pushNodesByBackendIdsToFrontend",
              {
                backendNodeIds: [backendNodeId]
              }
            );
            console.log("[CDP Element Helper] pushNodesByBackendIdsToFrontend 结果:", pushResult);
            const nodeIds = pushResult == null ? void 0 : pushResult.nodeIds;
            if (!nodeIds || nodeIds.length === 0 || nodeIds[0] === 0) {
              console.error(
                `[CDP Element Helper] 无法将 backendNodeId ${backendNodeId} 转换为 nodeId. 返回结果: ${JSON.stringify(pushResult)}`
              );
              return {
                error: `Failed to resolve backend node ID to node ID. BackendNodeId: ${backendNodeId}, Result: ${JSON.stringify(pushResult)}`
              };
            }
            const nodeId = nodeIds[0];
            const boxModelResult = yield cdpDebuggerManager.sendCommand(tabId, "DOM.getBoxModel", {
              nodeId
            });
            if (!boxModelResult || !boxModelResult.model) {
              return { error: "Failed to get box model for element" };
            }
            const content = boxModelResult.model.content;
            if (!content || content.length < 8) {
              return { error: "Invalid box model data" };
            }
            const x1 = content[0];
            const y1 = content[1];
            const x2 = content[2];
            const y2 = content[3];
            const x3 = content[4];
            const y3 = content[5];
            const x4 = content[6];
            const y4 = content[7];
            const left = Math.min(x1, x2, x3, x4);
            const right = Math.max(x1, x2, x3, x4);
            const top = Math.min(y1, y2, y3, y4);
            const bottom = Math.max(y1, y2, y3, y4);
            const width = right - left;
            const height = bottom - top;
            const rect = {
              x: left,
              y: top,
              width,
              height,
              top,
              right,
              bottom,
              left
            };
            const centerX = left + width / 2;
            const centerY = top + height / 2;
            return {
              centerX,
              centerY,
              rect
            };
          } finally {
            yield cdpDebuggerManager.sendCommand(tabId, "DOM.disable", {});
          }
        } catch (error2) {
          console.error("[CDP Element Helper] Error getting element by backend node ID:", error2);
          return {
            error: `Failed to get element position: ${error2 instanceof Error ? error2.message : String(error2)}`
          };
        }
      });
    }
  }
  const cdpElementHelper = new CDPElementHelper();
  class CDPInteractiveElementsHelper {
    constructor() {
      // 缓存 helper 代码(避免重复序列化)
      __publicField2(this, "helperCodeCache", null);
    }
    /**
     * 查找交互式元素
     * @param session CDP Session
     * @param options 查询选项
     * @returns 元素信息列表
     */
    findElements(session, options) {
      return __async(this, null, function* () {
        var _a3, _b2;
        const helperCode = this.getHelperCode();
        const expression = `
      (function() {
        ${helperCode}

        // 执行查询
        const options = ${JSON.stringify(options)};
        return findElementsByTextWithFallback(options);
      })()
    `;
        console.log("[CDPInteractiveElementsHelper] 开始执行 Runtime.evaluate");
        try {
          const result2 = yield session.send("Runtime.evaluate", {
            expression,
            returnByValue: true,
            awaitPromise: false,
            userGesture: false
          });
          if (result2.exceptionDetails) {
            const errorText = ((_a3 = result2.exceptionDetails.exception) == null ? void 0 : _a3.description) || result2.exceptionDetails.text || "Unknown error";
            throw new Error(`Runtime.evaluate 执行失败: ${errorText}`);
          }
          const elements = ((_b2 = result2.result) == null ? void 0 : _b2.value) || [];
          console.log(
            `[CDPInteractiveElementsHelper] Runtime.evaluate 成功,找到 ${elements.length} 个元素`
          );
          return elements;
        } catch (error2) {
          console.error("[CDPInteractiveElementsHelper] Runtime.evaluate 失败:", error2);
          throw error2;
        }
      });
    }
    /**
     * 通过 selector 查找元素
     * @param session CDP Session
     * @param selector CSS 选择器
     * @param options 查询选项
     * @returns 元素信息列表
     */
    findElementsBySelector(session, selector, options) {
      return __async(this, null, function* () {
        var _a3, _b2;
        const helperCode = this.getHelperCode();
        const expression = `
      (function() {
        ${helperCode}

        const selector = ${JSON.stringify(selector)};
        const includeCoordinates = ${options.includeCoordinates};

        // 查询所有匹配的元素
        const elements = Array.from(document.querySelectorAll(selector));

        const results = [];
        for (const el of elements) {
          // 检查可见性和可交互性
          if (!isElementVisible(el) || !isElementInteractive(el)) continue;

          // 判断元素类型
          let elementType = 'unknown';
          for (const [type, typeSelector] of Object.entries(ELEMENT_CONFIG)) {
            if (el.matches(typeSelector)) {
              elementType = type;
              break;
            }
          }

          results.push(createElementInfo(el, elementType, includeCoordinates));
        }

        return results;
      })()
    `;
        console.log(`[CDPInteractiveElementsHelper] Selector 查询: ${selector}`);
        try {
          const result2 = yield session.send("Runtime.evaluate", {
            expression,
            returnByValue: true,
            awaitPromise: false,
            userGesture: false
          });
          if (result2.exceptionDetails) {
            const errorText = ((_a3 = result2.exceptionDetails.exception) == null ? void 0 : _a3.description) || result2.exceptionDetails.text || "Unknown error";
            throw new Error(`Runtime.evaluate 执行失败: ${errorText}`);
          }
          const elements = ((_b2 = result2.result) == null ? void 0 : _b2.value) || [];
          console.log(
            `[CDPInteractiveElementsHelper] Selector 查询成功,找到 ${elements.length} 个元素`
          );
          return elements;
        } catch (error2) {
          console.error("[CDPInteractiveElementsHelper] Selector 查询失败:", error2);
          throw error2;
        }
      });
    }
    /**
     * 通过坐标查找元素
     * @param session CDP Session
     * @param x X 坐标
     * @param y Y 坐标
     * @param options 查询选项
     * @returns 元素信息列表
     */
    findElementsByCoordinates(session, x, y, options) {
      return __async(this, null, function* () {
        var _a3, _b2;
        const helperCode = this.getHelperCode();
        const expression = `
      (function() {
        ${helperCode}

        const x = ${x};
        const y = ${y};
        const includeCoordinates = ${options.includeCoordinates};

        // 获取该位置的所有元素
        const elementsAtPoint = document.elementsFromPoint(x, y);

        // 过滤扩展元素
        const filteredElements = elementsAtPoint.filter(
          el => !el.id?.startsWith('mcp-') && !el.id?.startsWith('chrome-mcp-')
        );

        const results = [];
        for (const el of filteredElements) {
          // 只返回可见和可交互的元素
          if (!isElementVisible(el) || !isElementInteractive(el)) continue;

          // 判断元素类型
          let elementType = 'unknown';
          for (const [type, typeSelector] of Object.entries(ELEMENT_CONFIG)) {
            if (el.matches(typeSelector)) {
              elementType = type;
              break;
            }
          }

          results.push(createElementInfo(el, elementType, includeCoordinates));
        }

        return results;
      })()
    `;
        console.log(`[CDPInteractiveElementsHelper] 坐标查询: (${x}, ${y})`);
        try {
          const result2 = yield session.send("Runtime.evaluate", {
            expression,
            returnByValue: true,
            awaitPromise: false,
            userGesture: false
          });
          if (result2.exceptionDetails) {
            const errorText = ((_a3 = result2.exceptionDetails.exception) == null ? void 0 : _a3.description) || result2.exceptionDetails.text || "Unknown error";
            throw new Error(`Runtime.evaluate 执行失败: ${errorText}`);
          }
          const elements = ((_b2 = result2.result) == null ? void 0 : _b2.value) || [];
          console.log(`[CDPInteractiveElementsHelper] 坐标查询成功,找到 ${elements.length} 个元素`);
          return elements;
        } catch (error2) {
          console.error("[CDPInteractiveElementsHelper] 坐标查询失败:", error2);
          throw error2;
        }
      });
    }
    /**
     * 获取 helper 代码(带缓存)
     * 从 interactive-elements-helper.js 提取核心函数
     */
    getHelperCode() {
      if (this.helperCodeCache) {
        return this.helperCodeCache;
      }
      this.helperCodeCache = `
      // ==================== 配置定义 ====================

      const ELEMENT_CONFIG = {
        button: 'button, input[type="button"], input[type="submit"], [role="button"]',
        link: 'a[href], [role="link"]',
        input: 'input:not([type="button"]):not([type="submit"]):not([type="checkbox"]):not([type="radio"])',
        checkbox: 'input[type="checkbox"], [role="checkbox"]',
        radio: 'input[type="radio"], [role="radio"]',
        textarea: 'textarea',
        select: 'select',
        tab: '[role="tab"]',
        interactive: '[onclick], [tabindex]:not([tabindex^="-"]), [role="menuitem"], [role="slider"], [role="option"], [role="treeitem"]'
      };

      const ANY_INTERACTIVE_SELECTOR = Object.values(ELEMENT_CONFIG).join(', ');

      // ==================== 核心函数 ====================

      /**
       * 检查元素是否可见
       */
      function isElementVisible(el) {
        if (!el || !el.isConnected) return false;

        const style = window.getComputedStyle(el);
        if (
          style.display === 'none' ||
          style.visibility === 'hidden' ||
          parseFloat(style.opacity) === 0
        ) {
          return false;
        }

        const rect = el.getBoundingClientRect();
        if (!(rect.width > 0 || rect.height > 0 || el.tagName === 'A')) {
          return false;
        }

        // 检查元素是否被其他元素遮挡
        return isElementActuallyClickable(el, rect);
      }

      /**
       * 检查元素在其位置是否真正可点击
       */
      function isElementActuallyClickable(el, rect) {
        // 计算元素中心点
        const centerX = rect.left + rect.width / 2;
        const centerY = rect.top + rect.height / 2;

        // 使用 elementsFromPoint 检查在该位置的所有元素
        const elements = document.elementsFromPoint(centerX, centerY);
        const topElement = elements.filter((e) => e.id !== 'mcp-page-protection-shadow-root')[0];

        if (!topElement) {
          return false;
        }

        // 如果最顶层元素就是目标元素或其子元素,则可点击
        if (topElement === el || el.contains(topElement)) {
          return true;
        }

        // 如果最顶层元素是目标元素的父元素,且父元素是透明的,则可能可点击
        if (topElement.contains(el)) {
          const topStyle = window.getComputedStyle(topElement);
          const topOpacity = parseFloat(topStyle.opacity);
          const topBackground = topStyle.backgroundColor;

          if (
            topOpacity < 1 ||
            topBackground === 'transparent' ||
            topBackground === 'rgba(0, 0, 0, 0)'
          ) {
            return true;
          }
        }

        // 检查 z-index 层级
        const elZIndex = getEffectiveZIndex(el);
        const topZIndex = getEffectiveZIndex(topElement);

        return elZIndex >= topZIndex;
      }

      /**
       * 获取元素的有效 z-index 值
       */
      function getEffectiveZIndex(el) {
        let currentEl = el;
        let maxZIndex = 0;

        while (currentEl && currentEl !== document.body) {
          const style = window.getComputedStyle(currentEl);
          const position = style.position;
          const zIndex = style.zIndex;

          // 只有定位元素的 z-index 才有效
          if (position !== 'static' && zIndex !== 'auto') {
            const numericZIndex = parseInt(zIndex, 10);
            if (!isNaN(numericZIndex)) {
              maxZIndex = Math.max(maxZIndex, numericZIndex);
            }
          }

          currentEl = currentEl.parentElement;
        }

        return maxZIndex;
      }

      /**
       * 检查元素是否可交互
       */
      function isElementInteractive(el) {
        if (el.hasAttribute('disabled') || el.getAttribute('aria-disabled') === 'true') {
          return false;
        }
        if (el.closest('[aria-hidden="true"]')) {
          return false;
        }
        return true;
      }

      /**
       * 生成稳定的 CSS 选择器
       */
      function generateSelector(el) {
        if (!(el instanceof Element)) return '';

        // 优先使用 ID
        if (el.id) {
          const idSelector = '#' + CSS.escape(el.id);
          if (document.querySelectorAll(idSelector).length === 1) return idSelector;
        }

        // 尝试使用常见的测试属性
        for (const attr of ['data-testid', 'data-cy', 'name']) {
          const attrValue = el.getAttribute(attr);
          if (attrValue) {
            const attrSelector = '[' + attr + '="' + CSS.escape(attrValue) + '"]';
            if (document.querySelectorAll(attrSelector).length === 1) return attrSelector;
          }
        }

        // 回退到路径选择器
        let path = '';
        let current = el;
        while (current && current.nodeType === Node.ELEMENT_NODE && current.tagName !== 'BODY') {
          let selector = current.tagName.toLowerCase();
          const parent = current.parentElement;
          if (parent) {
            const siblings = Array.from(parent.children).filter(
              (child) => child.tagName === current.tagName
            );
            if (siblings.length > 1) {
              const index = siblings.indexOf(current) + 1;
              selector += ':nth-of-type(' + index + ')';
            }
          }
          path = path ? selector + ' > ' + path : selector;
          current = parent;
        }
        return path ? 'body > ' + path : 'body';
      }

      /**
       * 获取元素的可访问名称
       */
      function getAccessibleName(el) {
        const labelledby = el.getAttribute('aria-labelledby');
        if (labelledby) {
          const labelElement = document.getElementById(labelledby);
          if (labelElement) return labelElement.textContent?.trim() || '';
        }
        const ariaLabel = el.getAttribute('aria-label');
        if (ariaLabel) return ariaLabel.trim();
        if (el.id) {
          const label = document.querySelector('label[for="' + el.id + '"]');
          if (label) return label.textContent?.trim() || '';
        }
        const parentLabel = el.closest('label');
        if (parentLabel) return parentLabel.textContent?.trim() || '';
        return (
          el.getAttribute('placeholder') ||
          el.getAttribute('value') ||
          el.textContent?.trim() ||
          el.getAttribute('title') ||
          ''
        );
      }

      /**
       * 模糊匹配
       */
      function fuzzyMatch(text, query) {
        if (!text || !query) return false;
        const lowerText = text.toLowerCase();
        const lowerQuery = query.toLowerCase();
        let textIndex = 0;
        let queryIndex = 0;
        while (textIndex < lowerText.length && queryIndex < lowerQuery.length) {
          if (lowerText[textIndex] === lowerQuery[queryIndex]) {
            queryIndex++;
          }
          textIndex++;
        }
        return queryIndex === lowerQuery.length;
      }

      /**
       * 创建元素信息对象
       */
      function createElementInfo(el, type, includeCoordinates, isInteractiveOverride = null) {
        const isActuallyInteractive = isElementInteractive(el);
        const info = {
          type,
          selector: generateSelector(el),
          text: getAccessibleName(el) || el.textContent?.trim(),
          isInteractive: isInteractiveOverride !== null ? isInteractiveOverride : isActuallyInteractive,
          disabled: el.hasAttribute('disabled') || el.getAttribute('aria-disabled') === 'true',
        };

        if (includeCoordinates) {
          const rect = el.getBoundingClientRect();
          info.coordinates = {
            x: rect.left + rect.width / 2,
            y: rect.top + rect.height / 2,
            rect: {
              x: rect.x,
              y: rect.y,
              width: rect.width,
              height: rect.height,
              top: rect.top,
              right: rect.right,
              bottom: rect.bottom,
              left: rect.left,
            },
          };
        }

        // 添加额外的属性
        if (el.href) info.href = el.href;
        if (el.type === 'checkbox' || el.type === 'radio') info.checked = el.checked;

        return info;
      }

      /**
       * 查找交互式元素 (Layer 1)
       */
      function findInteractiveElements(options = {}) {
        const { textQuery, includeCoordinates = true, types = Object.keys(ELEMENT_CONFIG) } = options;

        const selectorsToFind = types
          .map((type) => ELEMENT_CONFIG[type])
          .filter(Boolean)
          .join(', ');
        if (!selectorsToFind) return [];

        const targetElements = Array.from(document.querySelectorAll(selectorsToFind));
        const uniqueElements = new Set(targetElements);
        const results = [];

        for (const el of uniqueElements) {
          if (!isElementVisible(el) || !isElementInteractive(el)) continue;

          const accessibleName = getAccessibleName(el);
          if (textQuery && !fuzzyMatch(accessibleName, textQuery)) continue;

          let elementType = 'unknown';
          for (const [type, typeSelector] of Object.entries(ELEMENT_CONFIG)) {
            if (el.matches(typeSelector)) {
              elementType = type;
              break;
            }
          }
          results.push(createElementInfo(el, elementType, includeCoordinates));
        }
        return results;
      }

      /**
       * 3 层回退策略的主入口
       */
      function findElementsByTextWithFallback(options = {}) {
        const { textQuery, includeCoordinates = true } = options;

        if (!textQuery) {
          return findInteractiveElements({ ...options, types: Object.keys(ELEMENT_CONFIG) });
        }

        // Layer 1: 标准交互元素搜索
        let results = findInteractiveElements({ ...options, types: Object.keys(ELEMENT_CONFIG) });
        if (results.length > 0) {
          return results;
        }

        // Layer 2: 查找文本 → 查找交互式祖先
        const lowerCaseText = textQuery.toLowerCase();
        const xPath = '//text()[contains(translate(., "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz"), "' + lowerCaseText + '")]';
        const textNodes = document.evaluate(
          xPath,
          document,
          null,
          XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
          null
        );

        const interactiveElements = new Set();
        if (textNodes.snapshotLength > 0) {
          for (let i = 0; i < textNodes.snapshotLength; i++) {
            const parentElement = textNodes.snapshotItem(i).parentElement;
            if (parentElement) {
              const interactiveAncestor = parentElement.closest(ANY_INTERACTIVE_SELECTOR);
              if (
                interactiveAncestor &&
                isElementVisible(interactiveAncestor) &&
                isElementInteractive(interactiveAncestor)
              ) {
                interactiveElements.add(interactiveAncestor);
              }
            }
          }

          if (interactiveElements.size > 0) {
            return Array.from(interactiveElements).map((el) => {
              let elementType = 'interactive';
              for (const [type, typeSelector] of Object.entries(ELEMENT_CONFIG)) {
                if (el.matches(typeSelector)) {
                  elementType = type;
                  break;
                }
              }
              return createElementInfo(el, elementType, includeCoordinates);
            });
          }
        }

        // Layer 3: 返回包含文本的任何元素
        const leafElements = new Set();
        for (let i = 0; i < textNodes.snapshotLength; i++) {
          const parentElement = textNodes.snapshotItem(i).parentElement;
          if (parentElement && isElementVisible(parentElement)) {
            leafElements.add(parentElement);
          }
        }

        const finalElements = Array.from(leafElements).filter((el) => {
          return ![...leafElements].some((otherEl) => el !== otherEl && el.contains(otherEl));
        });

        return finalElements.map((el) => createElementInfo(el, 'text', includeCoordinates, true));
      }
    `;
      return this.helperCodeCache;
    }
  }
  const cdpInteractiveElementsHelper = new CDPInteractiveElementsHelper();
  class CDPHighlighter {
    /**
     * 在页面上高亮显示一个点（用于点击、滚动触发点等）
     * @param tabId - 标签页 ID
     * @param x - X 坐标
     * @param y - Y 坐标
     * @param color - 高亮颜色配置
     * @param duration - 高亮持续时间（毫秒），默认 1500ms
     */
    highlightPoint(_0, _1, _2) {
      return __async(this, arguments, function* (tabId, x, y, color = HIGHLIGHT_COLORS.RED, duration2 = 1500) {
        try {
          yield cdpDebuggerManager.sendCommand(tabId, "Runtime.evaluate", {
            expression: `
          (function() {
            // 移除之前的高亮点
            const oldMarker = document.getElementById('cdp-point-marker');
            if (oldMarker) {
              oldMarker.remove();
            }

            // 创建高亮点
            const marker = document.createElement('div');
            marker.id = 'cdp-point-marker';
            marker.style.cssText = \`
              position: fixed;
              left: \${${x} - 15}px;
              top: \${${y} - 15}px;
              width: 30px;
              height: 30px;
              background: radial-gradient(circle, ${color.primary.replace("#", "rgba(").replace(/(..)(..)(..)/, "$1, $2, $3,")}, 0.8) 0%, ${color.secondary} 60%, transparent 100%);
              border: 3px solid ${color.primary};
              border-radius: 50%;
              pointer-events: none;
              z-index: 2147483647;
              animation: cdp-point-pulse 0.6s ease-out;
            \`;

            // 添加动画样式
            if (!document.getElementById('cdp-point-animation-style')) {
              const style = document.createElement('style');
              style.id = 'cdp-point-animation-style';
              style.textContent = \`
                @keyframes cdp-point-pulse {
                  0% {
                    transform: scale(0.3);
                    opacity: 0;
                  }
                  50% {
                    transform: scale(1.3);
                    opacity: 1;
                  }
                  100% {
                    transform: scale(1);
                    opacity: 1;
                  }
                }
              \`;
              document.head.appendChild(style);
            }

            document.body.appendChild(marker);

            // 自动移除
            setTimeout(() => {
              marker.remove();
            }, ${duration2});
          })()
        `
          });
          console.log(`[CDP 高亮] 点位已高亮显示 (${x}, ${y})`);
        } catch (error2) {
          console.warn("[CDP 高亮] 高亮显示点位失败:", error2);
        }
      });
    }
    /**
     * 在页面上高亮显示一个元素（用于填充、滚动到视图等）
     * @param tabId - 标签页 ID
     * @param selector - CSS 选择器
     * @param color - 高亮颜色配置
     * @param duration - 高亮持续时间（毫秒），默认 1500ms
     */
    highlightElement(_0, _1) {
      return __async(this, arguments, function* (tabId, selector, color = HIGHLIGHT_COLORS.RED, duration2 = 1500) {
        try {
          yield cdpDebuggerManager.sendCommand(tabId, "Runtime.evaluate", {
            expression: `
          (function() {
            const element = document.querySelector(${JSON.stringify(selector)});
            if (!element) return;

            // 移除之前的高亮
            const oldHighlight = document.getElementById('cdp-element-highlight');
            if (oldHighlight) {
              oldHighlight.remove();
            }

            const rect = element.getBoundingClientRect();
            
            // 创建高亮边框
            const highlight = document.createElement('div');
            highlight.id = 'cdp-element-highlight';
            highlight.style.cssText = \`
              position: fixed;
              left: \${rect.left - 2}px;
              top: \${rect.top - 2}px;
              width: \${rect.width + 4}px;
              height: \${rect.height + 4}px;
              border: 2px solid ${color.primary};
              background: ${color.secondary};
              pointer-events: none;
              z-index: 2147483647;
              animation: cdp-element-pulse 0.6s ease-out;
              box-shadow: 0 0 10px ${color.secondary};
            \`;

            // 添加动画样式
            if (!document.getElementById('cdp-element-animation-style')) {
              const style = document.createElement('style');
              style.id = 'cdp-element-animation-style';
              style.textContent = \`
                @keyframes cdp-element-pulse {
                  0% {
                    opacity: 0;
                    transform: scale(0.98);
                  }
                  50% {
                    opacity: 1;
                    transform: scale(1.02);
                  }
                  100% {
                    opacity: 1;
                    transform: scale(1);
                  }
                }
              \`;
              document.head.appendChild(style);
            }

            document.body.appendChild(highlight);

            // 自动移除
            setTimeout(() => {
              highlight.remove();
            }, ${duration2});
          })()
        `
          });
          console.log(`[CDP 高亮] 元素已高亮显示: ${selector}`);
        } catch (error2) {
          console.warn("[CDP 高亮] 高亮显示元素失败:", error2);
        }
      });
    }
    /**
     * 移除所有高亮标记
     * @param tabId - 标签页 ID
     */
    removeAllHighlights(tabId) {
      return __async(this, null, function* () {
        try {
          yield cdpDebuggerManager.sendCommand(tabId, "Runtime.evaluate", {
            expression: `
          (function() {
            const pointMarker = document.getElementById('cdp-point-marker');
            if (pointMarker) pointMarker.remove();
            
            const elementHighlight = document.getElementById('cdp-element-highlight');
            if (elementHighlight) elementHighlight.remove();
          })()
        `
          });
          console.log("[CDP 高亮] 所有高亮标记已移除");
        } catch (error2) {
          console.warn("[CDP 高亮] 移除高亮标记失败:", error2);
        }
      });
    }
    /**
     * 高亮点击位置（便捷方法）
     */
    highlightClick(tabId, x, y) {
      return __async(this, null, function* () {
        return this.highlightPoint(tabId, x, y, HIGHLIGHT_COLORS.RED, 1500);
      });
    }
    /**
     * 高亮滚动触发点（便捷方法）
     */
    highlightScroll(tabId, x, y) {
      return __async(this, null, function* () {
        return this.highlightPoint(tabId, x, y, HIGHLIGHT_COLORS.RED, 2e3);
      });
    }
    /**
     * 高亮填充元素（便捷方法）
     */
    highlightFill(tabId, selector) {
      return __async(this, null, function* () {
        return this.highlightElement(tabId, selector, HIGHLIGHT_COLORS.RED, 1500);
      });
    }
  }
  const cdpHighlighter = new CDPHighlighter();
  class CDPScrollHelper {
    /**
     * 获取当前滚动位置
     * @param tabId - 标签页 ID
     * @returns 当前滚动位置
     */
    getCurrentScrollPosition(tabId) {
      return __async(this, null, function* () {
        return yield cdpElementHelper.getCurrentScrollPosition(tabId);
      });
    }
    /**
     * 使用 CDP 发送滚动事件
     * @param tabId - 标签页 ID
     * @param deltaX - X 轴滚动增量
     * @param deltaY - Y 轴滚动增量
     * @param x - 鼠标事件触发的 X 坐标（默认视口中心）
     * @param y - 鼠标事件触发的 Y 坐标（默认视口中心）
     * @param waitTime - 等待滚动完成的时间（毫秒），默认 300ms
     */
    scrollByDelta(tabId, deltaX, deltaY, x, y, waitTime = 300) {
      return __async(this, null, function* () {
        if (x === void 0 || y === void 0) {
          const viewport = yield cdpElementHelper.getViewportInfo(tabId);
          x = viewport.width / 2;
          y = viewport.height / 2;
        }
        try {
          console.log(
            `[CDP 滚动] 尝试使用 synthesizeScrollGesture: deltaX=${deltaX}, deltaY=${deltaY}, x=${x}, y=${y}`
          );
          yield cdpDebuggerManager.sendCommand(tabId, "Input.synthesizeScrollGesture", {
            x,
            y,
            xDistance: -deltaX,
            // 注意：方向相反
            yDistance: -deltaY,
            // 注意：方向相反
            xOverscroll: 0,
            yOverscroll: 0,
            preventFling: true,
            // 禁用惯性滚动，更精确
            speed: 800,
            // 滚动速度（像素/秒）
            gestureSourceType: "mouse",
            // 使用鼠标手势类型
            repeatCount: 1,
            repeatDelayMs: 0,
            interactionMarkerName: "mcp-scroll"
          });
          console.log(`[CDP 滚动] ✅ synthesizeScrollGesture 成功`);
        } catch (error2) {
          console.warn(`[CDP 滚动] ⚠️ synthesizeScrollGesture 失败，降级到 mouseWheel:`, error2);
          yield cdpDebuggerManager.sendCommand(tabId, "Input.dispatchMouseEvent", {
            type: "mouseWheel",
            x,
            y,
            deltaX,
            deltaY,
            modifiers: 0
          });
          console.log(
            `[CDP 滚动] mouseWheel 事件已发送: deltaX=${deltaX}, deltaY=${deltaY}, x=${x}, y=${y}`
          );
        }
        if (waitTime > 0) {
          yield new Promise((resolve2) => setTimeout(resolve2, waitTime));
        }
      });
    }
    /**
     * 滚动到指定位置
     * @param tabId - 标签页 ID
     * @param targetX - 目标 X 坐标
     * @param targetY - 目标 Y 坐标
     * @param x - 鼠标事件触发的 X 坐标（默认视口中心）
     * @param y - 鼠标事件触发的 Y 坐标（默认视口中心）
     */
    scrollToPosition(tabId, targetX, targetY, x, y) {
      return __async(this, null, function* () {
        const currentPosition = yield this.getCurrentScrollPosition(tabId);
        const deltaX = targetX - currentPosition.x;
        const deltaY = targetY - currentPosition.y;
        yield this.scrollByDelta(tabId, deltaX, deltaY, x, y);
      });
    }
    /**
     * 检查元素是否需要滚动才能进入视口
     * @param tabId - 标签页 ID
     * @param selector - CSS 选择器
     * @returns 是否需要滚动
     */
    needsScroll(tabId, selector) {
      return __async(this, null, function* () {
        const elementInfo = yield cdpElementHelper.findElement(tabId, selector, {
          includeViewport: true
        });
        if (elementInfo.error || !elementInfo.rect || !elementInfo.viewport) {
          return false;
        }
        const { rect, viewport } = elementInfo;
        return rect.top < 0 || rect.bottom > viewport.height || rect.left < 0 || rect.right > viewport.width;
      });
    }
    /**
     * 将元素滚动到视口中心
     * @param tabId - 标签页 ID
     * @param selector - CSS 选择器
     * @returns 是否执行了滚动操作
     */
    scrollElementToCenter(tabId, selector) {
      return __async(this, null, function* () {
        const elementInfo = yield cdpElementHelper.findElement(tabId, selector, {
          includeAbsolutePosition: true,
          includeViewport: true,
          includeScroll: true
        });
        if (elementInfo.error || !elementInfo.absolutePosition || !elementInfo.viewport) {
          console.warn(`[CDP 滚动] 无法获取元素信息: ${elementInfo.error || "Unknown error"}`);
          return false;
        }
        const { absolutePosition, viewport, currentScroll } = elementInfo;
        const needsScrolling = yield this.needsScroll(tabId, selector);
        if (!needsScrolling) {
          console.log("[CDP 滚动] 元素已在视口中，无需滚动");
          return false;
        }
        console.log("[CDP 滚动] 元素不在视口中心，需要滚动");
        const targetScrollX = absolutePosition.centerX - viewport.width / 2;
        const targetScrollY = absolutePosition.centerY - viewport.height / 2;
        const deltaX = targetScrollX - ((currentScroll == null ? void 0 : currentScroll.x) || 0);
        const deltaY = targetScrollY - ((currentScroll == null ? void 0 : currentScroll.y) || 0);
        console.log("[CDP 滚动] 滚动增量:", { deltaX, deltaY });
        const scrollX = viewport.width / 2;
        const scrollY = viewport.height / 2;
        yield this.scrollByDelta(tabId, deltaX, deltaY, scrollX, scrollY);
        return true;
      });
    }
    /**
     * 将元素滚动到视口指定位置
     * @param tabId - 标签页 ID
     * @param selector - CSS 选择器
     * @param block - 垂直对齐方式
     * @param inline - 水平对齐方式
     * @returns 是否执行了滚动操作
     */
    scrollElementIntoView(tabId, selector, block = "center", inline = "center") {
      return __async(this, null, function* () {
        const elementInfo = yield cdpElementHelper.findElement(tabId, selector, {
          includeAbsolutePosition: true,
          includeViewport: true,
          includeScroll: true
        });
        if (elementInfo.error || !elementInfo.absolutePosition || !elementInfo.viewport || !elementInfo.rect) {
          console.warn(`[CDP 滚动] 无法获取元素信息: ${elementInfo.error || "Unknown error"}`);
          return false;
        }
        const { absolutePosition, viewport, currentScroll, rect } = elementInfo;
        const scroll = currentScroll || { x: 0, y: 0 };
        const scrollTarget = this.calculateScrollTarget(
          absolutePosition,
          rect,
          viewport,
          scroll,
          block,
          inline
        );
        const deltaX = scrollTarget.targetScrollX - scroll.x;
        const deltaY = scrollTarget.targetScrollY - scroll.y;
        const needsScrolling = Math.abs(deltaX) > 1 || Math.abs(deltaY) > 1;
        if (!needsScrolling) {
          console.log("[CDP 滚动] 元素已在目标位置，无需滚动");
          return false;
        }
        console.log("[CDP 滚动] 滚动增量:", { deltaX, deltaY });
        const scrollEventX = viewport.width / 2;
        const scrollEventY = viewport.height / 2;
        yield this.scrollByDelta(tabId, deltaX, deltaY, scrollEventX, scrollEventY);
        return true;
      });
    }
    /**
     * 计算滚动目标位置
     */
    calculateScrollTarget(absolutePosition, rect, viewport, currentScroll, block, inline) {
      let targetScrollX = currentScroll.x;
      let targetScrollY = currentScroll.y;
      switch (block) {
        case "start":
          targetScrollY = absolutePosition.top;
          break;
        case "center":
          targetScrollY = absolutePosition.centerY - viewport.height / 2;
          break;
        case "end":
          targetScrollY = absolutePosition.bottom - viewport.height;
          break;
        case "nearest":
          if (rect.top < 0) {
            targetScrollY = absolutePosition.top;
          } else if (rect.bottom > viewport.height) {
            targetScrollY = absolutePosition.bottom - viewport.height;
          }
          break;
      }
      switch (inline) {
        case "start":
          targetScrollX = absolutePosition.left;
          break;
        case "center":
          targetScrollX = absolutePosition.centerX - viewport.width / 2;
          break;
        case "end":
          targetScrollX = absolutePosition.right - viewport.width;
          break;
        case "nearest":
          if (rect.left < 0) {
            targetScrollX = absolutePosition.left;
          } else if (rect.right > viewport.width) {
            targetScrollX = absolutePosition.right - viewport.width;
          }
          break;
      }
      return { targetScrollX, targetScrollY };
    }
    /**
     * 通过 backendNodeId 将元素滚动到视口中心
     * @param tabId - 标签页 ID
     * @param backendNodeId - 后端节点 ID
     * @returns 是否执行了滚动操作
     */
    scrollElementByBackendNodeIdToCenter(tabId, backendNodeId) {
      return __async(this, null, function* () {
        try {
          const elementPosition = yield cdpElementHelper.getElementByBackendNodeId(
            tabId,
            backendNodeId
          );
          if ("error" in elementPosition) {
            console.warn(`[CDP 滚动] 无法通过 backendNodeId 获取元素位置: ${elementPosition.error}`);
            return false;
          }
          const { rect } = elementPosition;
          const viewport = yield cdpElementHelper.getViewportInfo(tabId);
          const isInViewport = rect.top >= 0 && rect.bottom <= viewport.height && rect.left >= 0 && rect.right <= viewport.width;
          if (isInViewport) {
            console.log("[CDP 滚动] 元素已在视口中，无需滚动");
            return false;
          }
          console.log("[CDP 滚动] 元素不在视口中，需要滚动");
          const currentScroll = yield this.getCurrentScrollPosition(tabId);
          const absoluteCenterX = rect.left + currentScroll.x + rect.width / 2;
          const absoluteCenterY = rect.top + currentScroll.y + rect.height / 2;
          const targetScrollX = absoluteCenterX - viewport.width / 2;
          const targetScrollY = absoluteCenterY - viewport.height / 2;
          const deltaX = targetScrollX - currentScroll.x;
          const deltaY = targetScrollY - currentScroll.y;
          console.log("[CDP 滚动] 滚动增量:", { deltaX, deltaY });
          const scrollX = viewport.width / 2;
          const scrollY = viewport.height / 2;
          yield this.scrollByDelta(tabId, deltaX, deltaY, scrollX, scrollY);
          return true;
        } catch (error2) {
          console.error("[CDP 滚动] 通过 backendNodeId 滚动元素失败:", error2);
          return false;
        }
      });
    }
    /**
     * 获取滚动信息（用于调试和结果返回）
     * @param tabId - 标签页 ID
     * @returns 滚动信息
     */
    getScrollInfo(tabId) {
      return __async(this, null, function* () {
        var _a3;
        const expression = `
      (function() {
        const scrollX = window.pageXOffset || window.scrollX || document.documentElement.scrollLeft || document.body.scrollLeft || 0;
        const scrollY = window.pageYOffset || window.scrollY || document.documentElement.scrollTop || document.body.scrollTop || 0;
        
        return {
          scrollX: scrollX,
          scrollY: scrollY,
          scrollWidth: document.documentElement.scrollWidth || document.body.scrollWidth,
          scrollHeight: document.documentElement.scrollHeight || document.body.scrollHeight,
          clientWidth: window.innerWidth || document.documentElement.clientWidth,
          clientHeight: window.innerHeight || document.documentElement.clientHeight
        };
      })()
    `;
        const result2 = yield cdpDebuggerManager.sendCommand(tabId, "Runtime.evaluate", {
          expression,
          returnByValue: true
        });
        return ((_a3 = result2 == null ? void 0 : result2.result) == null ? void 0 : _a3.value) || {
          scrollX: 0,
          scrollY: 0,
          scrollWidth: 0,
          scrollHeight: 0,
          clientWidth: 0,
          clientHeight: 0
        };
      });
    }
  }
  const cdpScrollHelper = new CDPScrollHelper();
  function isCDPUnsupportedUrl(url2) {
    if (!url2) return false;
    const unsupportedPrefixes = [
      "chrome://",
      "chrome-extension://",
      "edge://",
      "about:",
      "devtools://"
    ];
    return unsupportedPrefixes.some((prefix) => url2.startsWith(prefix));
  }
  function navigateWithTraditionalAPI(url2, tabId, active) {
    return __async(this, null, function* () {
      console.log("[传统导航] 使用 chrome.tabs API 导航");
      const navigateStartTime = Date.now();
      const currentTab = yield chrome.tabs.get(tabId);
      if (isCDPUnsupportedUrl(currentTab.url)) {
        console.log("[传统导航] 当前页面为内部页面，先导航到 about:blank");
        yield chrome.tabs.update(tabId, { url: "about:blank" });
        yield new Promise((resolve2) => setTimeout(resolve2, 100));
      }
      yield chrome.tabs.update(tabId, { url: url2, active });
      yield new Promise((resolve2) => setTimeout(resolve2, 300));
      const loadTime = Date.now() - navigateStartTime;
      const finalTab = yield chrome.tabs.get(tabId);
      return success$1(
        `Successfully navigated to ${url2} in ${active ? "foreground" : "background"} (traditional API)`,
        {
          tabId,
          windowId: finalTab.windowId,
          url: finalTab.url,
          title: finalTab.title,
          loadTime,
          active,
          method: "traditional"
        }
      );
    });
  }
  const navigateCdpSchema = {
    url: string$1().url().describe("URL to navigate to"),
    tabId: number$1().int().positive().optional().describe(
      "(DEPRECATED: This parameter is now ignored) Always creates a new tab. This parameter is kept for backward compatibility but no longer affects behavior."
    ),
    active: boolean$1().default(false).describe(
      "Whether to activate (bring to foreground) the tab. Default: false (background navigation). IMPORTANT: Keep this as false to avoid interrupting the user. Only set to true if the user explicitly requests to view the page or if immediate user interaction is required."
    )
  };
  class NavigateToolCDP extends BaseBrowserToolExecutor {
    constructor() {
      super(...arguments);
      __publicField2(this, "name", TOOL_NAMES.BROWSER.NAVIGATE);
      __publicField2(this, "description", "Navigate to a URL in a NEW tab with intelligent implementation selection. Always creates a new tab (tabId parameter is deprecated). Automatically uses CDP for normal pages or traditional Chrome API for internal pages (chrome://, about:, etc.). Supports background navigation. Returns immediately after initiating navigation without waiting for page load. For ensuring page readiness, use other tools (e.g., get-interactive-elements, screenshot) after navigation. Ideal for automation tasks requiring fast, reliable navigation with clean browser state.");
      __publicField2(this, "annotations", {
        title: "Navigate (CDP)",
        category: ToolCategory.NAVIGATION,
        readOnlyHint: false
      });
      __publicField2(this, "schema", navigateCdpSchema);
    }
    execute(args, context) {
      return __async(this, null, function* () {
        console.log("[CDP 导航] 开始执行，参数:", args);
        const validationResult = this.validateArgs(args);
        if (!validationResult.success) {
          return validationResult.error;
        }
        const { url: url2, tabId, active } = validationResult.data;
        console.log("[CDP 导航] 创建新 tab, active:", active);
        if (tabId !== void 0) {
          console.log("[CDP 导航] 注意: tabId 参数已被忽略，始终创建新标签页");
        }
        const targetTab = yield createTab({
          url: "about:blank",
          // 先创建空白页
          active,
          sessionId: context == null ? void 0 : context.sessionId
          // 传入 sessionId 以加入 tab group
        });
        const createdNewTab = true;
        console.log("[CDP 导航] 新 tab 已创建:", targetTab.id);
        const targetTabId = targetTab.id;
        const needsTraditionalAPI = isCDPUnsupportedUrl(url2);
        if (needsTraditionalAPI) {
          console.warn(`[CDP 导航] 降级为传统 API: 目标 URL (${url2}) 不支持 CDP`);
          return yield navigateWithTraditionalAPI(url2, targetTabId, active);
        }
        return yield cdpSessionExecutor.executeWithSession(targetTabId, (session, viewport) => __async(this, null, function* () {
          try {
            const navigateStartTime = Date.now();
            console.log("[CDP 导航] 开始导航到:", url2);
            const navigateResult = yield session.send("Page.navigate", {
              url: url2
            });
            if (navigateResult.errorText) {
              return error$J(`Navigation failed: ${navigateResult.errorText}`, "NAVIGATION_ERROR", {
                errorText: navigateResult.errorText,
                url: url2
              });
            }
            console.log("[CDP 导航] Page.navigate 命令已发送, frameId:", navigateResult.frameId);
            yield new Promise((resolve2) => setTimeout(resolve2, 300));
            console.log("[CDP 导航] 导航命令已处理");
            const loadTime = Date.now() - navigateStartTime;
            const finalTab = yield chrome.tabs.get(targetTabId);
            console.log("[CDP 导航] 导航成功完成, 耗时:", loadTime, "ms");
            return success$1(
              `Successfully navigated to ${url2} in ${active ? "foreground" : "background"}`,
              {
                tabId: targetTabId,
                windowId: finalTab.windowId,
                url: finalTab.url,
                title: finalTab.title,
                loadTime,
                active,
                created: createdNewTab
              }
            );
          } catch (err) {
            console.error("[CDP 导航] 导航错误:", err);
            return error$J(
              `执行导航时出错: ${err instanceof Error ? err.message : String(err)}`,
              "EXECUTION_ERROR",
              {
                stack: err instanceof Error ? err.stack : void 0
              }
            );
          }
        }));
      });
    }
  }
  const navigateToolCDP = new NavigateToolCDP();
  const turndownJs = "var TurndownService = (function () {\n  'use strict';\n\n  function extend (destination) {\n    for (var i = 1; i < arguments.length; i++) {\n      var source = arguments[i];\n      for (var key in source) {\n        if (source.hasOwnProperty(key)) destination[key] = source[key];\n      }\n    }\n    return destination\n  }\n\n  function repeat (character, count) {\n    return Array(count + 1).join(character)\n  }\n\n  function trimLeadingNewlines (string) {\n    return string.replace(/^\\n*/, '')\n  }\n\n  function trimTrailingNewlines (string) {\n    // avoid match-at-end regexp bottleneck, see #370\n    var indexEnd = string.length;\n    while (indexEnd > 0 && string[indexEnd - 1] === '\\n') indexEnd--;\n    return string.substring(0, indexEnd)\n  }\n\n  function trimNewlines (string) {\n    return trimTrailingNewlines(trimLeadingNewlines(string))\n  }\n\n  var blockElements = [\n    'ADDRESS', 'ARTICLE', 'ASIDE', 'AUDIO', 'BLOCKQUOTE', 'BODY', 'CANVAS',\n    'CENTER', 'DD', 'DIR', 'DIV', 'DL', 'DT', 'FIELDSET', 'FIGCAPTION', 'FIGURE',\n    'FOOTER', 'FORM', 'FRAMESET', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'HEADER',\n    'HGROUP', 'HR', 'HTML', 'ISINDEX', 'LI', 'MAIN', 'MENU', 'NAV', 'NOFRAMES',\n    'NOSCRIPT', 'OL', 'OUTPUT', 'P', 'PRE', 'SECTION', 'TABLE', 'TBODY', 'TD',\n    'TFOOT', 'TH', 'THEAD', 'TR', 'UL'\n  ];\n\n  function isBlock (node) {\n    return is(node, blockElements)\n  }\n\n  var voidElements = [\n    'AREA', 'BASE', 'BR', 'COL', 'COMMAND', 'EMBED', 'HR', 'IMG', 'INPUT',\n    'KEYGEN', 'LINK', 'META', 'PARAM', 'SOURCE', 'TRACK', 'WBR'\n  ];\n\n  function isVoid (node) {\n    return is(node, voidElements)\n  }\n\n  function hasVoid (node) {\n    return has(node, voidElements)\n  }\n\n  var meaningfulWhenBlankElements = [\n    'A', 'TABLE', 'THEAD', 'TBODY', 'TFOOT', 'TH', 'TD', 'IFRAME', 'SCRIPT',\n    'AUDIO', 'VIDEO'\n  ];\n\n  function isMeaningfulWhenBlank (node) {\n    return is(node, meaningfulWhenBlankElements)\n  }\n\n  function hasMeaningfulWhenBlank (node) {\n    return has(node, meaningfulWhenBlankElements)\n  }\n\n  function is (node, tagNames) {\n    return tagNames.indexOf(node.nodeName) >= 0\n  }\n\n  function has (node, tagNames) {\n    return (\n      node.getElementsByTagName &&\n      tagNames.some(function (tagName) {\n        return node.getElementsByTagName(tagName).length\n      })\n    )\n  }\n\n  var rules = {};\n\n  rules.paragraph = {\n    filter: 'p',\n\n    replacement: function (content) {\n      return '\\n\\n' + content + '\\n\\n'\n    }\n  };\n\n  rules.lineBreak = {\n    filter: 'br',\n\n    replacement: function (content, node, options) {\n      return options.br + '\\n'\n    }\n  };\n\n  rules.heading = {\n    filter: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'],\n\n    replacement: function (content, node, options) {\n      var hLevel = Number(node.nodeName.charAt(1));\n\n      if (options.headingStyle === 'setext' && hLevel < 3) {\n        var underline = repeat((hLevel === 1 ? '=' : '-'), content.length);\n        return (\n          '\\n\\n' + content + '\\n' + underline + '\\n\\n'\n        )\n      } else {\n        return '\\n\\n' + repeat('#', hLevel) + ' ' + content + '\\n\\n'\n      }\n    }\n  };\n\n  rules.blockquote = {\n    filter: 'blockquote',\n\n    replacement: function (content) {\n      content = trimNewlines(content).replace(/^/gm, '> ');\n      return '\\n\\n' + content + '\\n\\n'\n    }\n  };\n\n  rules.list = {\n    filter: ['ul', 'ol'],\n\n    replacement: function (content, node) {\n      var parent = node.parentNode;\n      if (parent.nodeName === 'LI' && parent.lastElementChild === node) {\n        return '\\n' + content\n      } else {\n        return '\\n\\n' + content + '\\n\\n'\n      }\n    }\n  };\n\n  rules.listItem = {\n    filter: 'li',\n\n    replacement: function (content, node, options) {\n      var prefix = options.bulletListMarker + '   ';\n      var parent = node.parentNode;\n      if (parent.nodeName === 'OL') {\n        var start = parent.getAttribute('start');\n        var index = Array.prototype.indexOf.call(parent.children, node);\n        prefix = (start ? Number(start) + index : index + 1) + '.  ';\n      }\n      var isParagraph = /\\n$/.test(content);\n      content = trimNewlines(content) + (isParagraph ? '\\n' : '');\n      content = content.replace(/\\n/gm, '\\n' + ' '.repeat(prefix.length)); // indent\n      return (\n        prefix + content + (node.nextSibling ? '\\n' : '')\n      )\n    }\n  };\n\n  rules.indentedCodeBlock = {\n    filter: function (node, options) {\n      return (\n        options.codeBlockStyle === 'indented' &&\n        node.nodeName === 'PRE' &&\n        node.firstChild &&\n        node.firstChild.nodeName === 'CODE'\n      )\n    },\n\n    replacement: function (content, node, options) {\n      return (\n        '\\n\\n    ' +\n        node.firstChild.textContent.replace(/\\n/g, '\\n    ') +\n        '\\n\\n'\n      )\n    }\n  };\n\n  rules.fencedCodeBlock = {\n    filter: function (node, options) {\n      return (\n        options.codeBlockStyle === 'fenced' &&\n        node.nodeName === 'PRE' &&\n        node.firstChild &&\n        node.firstChild.nodeName === 'CODE'\n      )\n    },\n\n    replacement: function (content, node, options) {\n      var className = node.firstChild.getAttribute('class') || '';\n      var language = (className.match(/language-(\\S+)/) || [null, ''])[1];\n      var code = node.firstChild.textContent;\n\n      var fenceChar = options.fence.charAt(0);\n      var fenceSize = 3;\n      var fenceInCodeRegex = new RegExp('^' + fenceChar + '{3,}', 'gm');\n\n      var match;\n      while ((match = fenceInCodeRegex.exec(code))) {\n        if (match[0].length >= fenceSize) {\n          fenceSize = match[0].length + 1;\n        }\n      }\n\n      var fence = repeat(fenceChar, fenceSize);\n\n      return (\n        '\\n\\n' + fence + language + '\\n' +\n        code.replace(/\\n$/, '') +\n        '\\n' + fence + '\\n\\n'\n      )\n    }\n  };\n\n  rules.horizontalRule = {\n    filter: 'hr',\n\n    replacement: function (content, node, options) {\n      return '\\n\\n' + options.hr + '\\n\\n'\n    }\n  };\n\n  rules.inlineLink = {\n    filter: function (node, options) {\n      return (\n        options.linkStyle === 'inlined' &&\n        node.nodeName === 'A' &&\n        node.getAttribute('href')\n      )\n    },\n\n    replacement: function (content, node) {\n      var href = node.getAttribute('href');\n      if (href) href = href.replace(/([()])/g, '\\\\$1');\n      var title = cleanAttribute(node.getAttribute('title'));\n      if (title) title = ' \"' + title.replace(/\"/g, '\\\\\"') + '\"';\n      return '[' + content + '](' + href + title + ')'\n    }\n  };\n\n  rules.referenceLink = {\n    filter: function (node, options) {\n      return (\n        options.linkStyle === 'referenced' &&\n        node.nodeName === 'A' &&\n        node.getAttribute('href')\n      )\n    },\n\n    replacement: function (content, node, options) {\n      var href = node.getAttribute('href');\n      var title = cleanAttribute(node.getAttribute('title'));\n      if (title) title = ' \"' + title + '\"';\n      var replacement;\n      var reference;\n\n      switch (options.linkReferenceStyle) {\n        case 'collapsed':\n          replacement = '[' + content + '][]';\n          reference = '[' + content + ']: ' + href + title;\n          break\n        case 'shortcut':\n          replacement = '[' + content + ']';\n          reference = '[' + content + ']: ' + href + title;\n          break\n        default:\n          var id = this.references.length + 1;\n          replacement = '[' + content + '][' + id + ']';\n          reference = '[' + id + ']: ' + href + title;\n      }\n\n      this.references.push(reference);\n      return replacement\n    },\n\n    references: [],\n\n    append: function (options) {\n      var references = '';\n      if (this.references.length) {\n        references = '\\n\\n' + this.references.join('\\n') + '\\n\\n';\n        this.references = []; // Reset references\n      }\n      return references\n    }\n  };\n\n  rules.emphasis = {\n    filter: ['em', 'i'],\n\n    replacement: function (content, node, options) {\n      if (!content.trim()) return ''\n      return options.emDelimiter + content + options.emDelimiter\n    }\n  };\n\n  rules.strong = {\n    filter: ['strong', 'b'],\n\n    replacement: function (content, node, options) {\n      if (!content.trim()) return ''\n      return options.strongDelimiter + content + options.strongDelimiter\n    }\n  };\n\n  rules.code = {\n    filter: function (node) {\n      var hasSiblings = node.previousSibling || node.nextSibling;\n      var isCodeBlock = node.parentNode.nodeName === 'PRE' && !hasSiblings;\n\n      return node.nodeName === 'CODE' && !isCodeBlock\n    },\n\n    replacement: function (content) {\n      if (!content) return ''\n      content = content.replace(/\\r?\\n|\\r/g, ' ');\n\n      var extraSpace = /^`|^ .*?[^ ].* $|`$/.test(content) ? ' ' : '';\n      var delimiter = '`';\n      var matches = content.match(/`+/gm) || [];\n      while (matches.indexOf(delimiter) !== -1) delimiter = delimiter + '`';\n\n      return delimiter + extraSpace + content + extraSpace + delimiter\n    }\n  };\n\n  rules.image = {\n    filter: 'img',\n\n    replacement: function (content, node) {\n      var alt = cleanAttribute(node.getAttribute('alt'));\n      var src = node.getAttribute('src') || '';\n      var title = cleanAttribute(node.getAttribute('title'));\n      var titlePart = title ? ' \"' + title + '\"' : '';\n      return src ? '![' + alt + ']' + '(' + src + titlePart + ')' : ''\n    }\n  };\n\n  function cleanAttribute (attribute) {\n    return attribute ? attribute.replace(/(\\n+\\s*)+/g, '\\n') : ''\n  }\n\n  /**\n   * Manages a collection of rules used to convert HTML to Markdown\n   */\n\n  function Rules (options) {\n    this.options = options;\n    this._keep = [];\n    this._remove = [];\n\n    this.blankRule = {\n      replacement: options.blankReplacement\n    };\n\n    this.keepReplacement = options.keepReplacement;\n\n    this.defaultRule = {\n      replacement: options.defaultReplacement\n    };\n\n    this.array = [];\n    for (var key in options.rules) this.array.push(options.rules[key]);\n  }\n\n  Rules.prototype = {\n    add: function (key, rule) {\n      this.array.unshift(rule);\n    },\n\n    keep: function (filter) {\n      this._keep.unshift({\n        filter: filter,\n        replacement: this.keepReplacement\n      });\n    },\n\n    remove: function (filter) {\n      this._remove.unshift({\n        filter: filter,\n        replacement: function () {\n          return ''\n        }\n      });\n    },\n\n    forNode: function (node) {\n      if (node.isBlank) return this.blankRule\n      var rule;\n\n      if ((rule = findRule(this.array, node, this.options))) return rule\n      if ((rule = findRule(this._keep, node, this.options))) return rule\n      if ((rule = findRule(this._remove, node, this.options))) return rule\n\n      return this.defaultRule\n    },\n\n    forEach: function (fn) {\n      for (var i = 0; i < this.array.length; i++) fn(this.array[i], i);\n    }\n  };\n\n  function findRule (rules, node, options) {\n    for (var i = 0; i < rules.length; i++) {\n      var rule = rules[i];\n      if (filterValue(rule, node, options)) return rule\n    }\n    return void 0\n  }\n\n  function filterValue (rule, node, options) {\n    var filter = rule.filter;\n    if (typeof filter === 'string') {\n      if (filter === node.nodeName.toLowerCase()) return true\n    } else if (Array.isArray(filter)) {\n      if (filter.indexOf(node.nodeName.toLowerCase()) > -1) return true\n    } else if (typeof filter === 'function') {\n      if (filter.call(rule, node, options)) return true\n    } else {\n      throw new TypeError('`filter` needs to be a string, array, or function')\n    }\n  }\n\n  /**\n   * The collapseWhitespace function is adapted from collapse-whitespace\n   * by Luc Thevenard.\n   *\n   * The MIT License (MIT)\n   *\n   * Copyright (c) 2014 Luc Thevenard <lucthevenard@gmail.com>\n   *\n   * Permission is hereby granted, free of charge, to any person obtaining a copy\n   * of this software and associated documentation files (the \"Software\"), to deal\n   * in the Software without restriction, including without limitation the rights\n   * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n   * copies of the Software, and to permit persons to whom the Software is\n   * furnished to do so, subject to the following conditions:\n   *\n   * The above copyright notice and this permission notice shall be included in\n   * all copies or substantial portions of the Software.\n   *\n   * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n   * THE SOFTWARE.\n   */\n\n  /**\n   * collapseWhitespace(options) removes extraneous whitespace from an the given element.\n   *\n   * @param {Object} options\n   */\n  function collapseWhitespace (options) {\n    var element = options.element;\n    var isBlock = options.isBlock;\n    var isVoid = options.isVoid;\n    var isPre = options.isPre || function (node) {\n      return node.nodeName === 'PRE'\n    };\n\n    if (!element.firstChild || isPre(element)) return\n\n    var prevText = null;\n    var keepLeadingWs = false;\n\n    var prev = null;\n    var node = next(prev, element, isPre);\n\n    while (node !== element) {\n      if (node.nodeType === 3 || node.nodeType === 4) { // Node.TEXT_NODE or Node.CDATA_SECTION_NODE\n        var text = node.data.replace(/[ \\r\\n\\t]+/g, ' ');\n\n        if ((!prevText || / $/.test(prevText.data)) &&\n            !keepLeadingWs && text[0] === ' ') {\n          text = text.substr(1);\n        }\n\n        // `text` might be empty at this point.\n        if (!text) {\n          node = remove(node);\n          continue\n        }\n\n        node.data = text;\n\n        prevText = node;\n      } else if (node.nodeType === 1) { // Node.ELEMENT_NODE\n        if (isBlock(node) || node.nodeName === 'BR') {\n          if (prevText) {\n            prevText.data = prevText.data.replace(/ $/, '');\n          }\n\n          prevText = null;\n          keepLeadingWs = false;\n        } else if (isVoid(node) || isPre(node)) {\n          // Avoid trimming space around non-block, non-BR void elements and inline PRE.\n          prevText = null;\n          keepLeadingWs = true;\n        } else if (prevText) {\n          // Drop protection if set previously.\n          keepLeadingWs = false;\n        }\n      } else {\n        node = remove(node);\n        continue\n      }\n\n      var nextNode = next(prev, node, isPre);\n      prev = node;\n      node = nextNode;\n    }\n\n    if (prevText) {\n      prevText.data = prevText.data.replace(/ $/, '');\n      if (!prevText.data) {\n        remove(prevText);\n      }\n    }\n  }\n\n  /**\n   * remove(node) removes the given node from the DOM and returns the\n   * next node in the sequence.\n   *\n   * @param {Node} node\n   * @return {Node} node\n   */\n  function remove (node) {\n    var next = node.nextSibling || node.parentNode;\n\n    node.parentNode.removeChild(node);\n\n    return next\n  }\n\n  /**\n   * next(prev, current, isPre) returns the next node in the sequence, given the\n   * current and previous nodes.\n   *\n   * @param {Node} prev\n   * @param {Node} current\n   * @param {Function} isPre\n   * @return {Node}\n   */\n  function next (prev, current, isPre) {\n    if ((prev && prev.parentNode === current) || isPre(current)) {\n      return current.nextSibling || current.parentNode\n    }\n\n    return current.firstChild || current.nextSibling || current.parentNode\n  }\n\n  /*\n   * Set up window for Node.js\n   */\n\n  var root = (typeof window !== 'undefined' ? window : {});\n\n  /*\n   * Parsing HTML strings\n   */\n\n  function canParseHTMLNatively () {\n    var Parser = root.DOMParser;\n    var canParse = false;\n\n    // Adapted from https://gist.github.com/1129031\n    // Firefox/Opera/IE throw errors on unsupported types\n    try {\n      // WebKit returns null on unsupported types\n      if (new Parser().parseFromString('', 'text/html')) {\n        canParse = true;\n      }\n    } catch (e) {}\n\n    return canParse\n  }\n\n  function createHTMLParser () {\n    var Parser = function () {};\n\n    {\n      if (shouldUseActiveX()) {\n        Parser.prototype.parseFromString = function (string) {\n          var doc = new window.ActiveXObject('htmlfile');\n          doc.designMode = 'on'; // disable on-page scripts\n          doc.open();\n          doc.write(string);\n          doc.close();\n          return doc\n        };\n      } else {\n        Parser.prototype.parseFromString = function (string) {\n          var doc = document.implementation.createHTMLDocument('');\n          doc.open();\n          doc.write(string);\n          doc.close();\n          return doc\n        };\n      }\n    }\n    return Parser\n  }\n\n  function shouldUseActiveX () {\n    var useActiveX = false;\n    try {\n      document.implementation.createHTMLDocument('').open();\n    } catch (e) {\n      if (root.ActiveXObject) useActiveX = true;\n    }\n    return useActiveX\n  }\n\n  var HTMLParser = canParseHTMLNatively() ? root.DOMParser : createHTMLParser();\n\n  function RootNode (input, options) {\n    var root;\n    if (typeof input === 'string') {\n      var doc = htmlParser().parseFromString(\n        // DOM parsers arrange elements in the <head> and <body>.\n        // Wrapping in a custom element ensures elements are reliably arranged in\n        // a single element.\n        '<x-turndown id=\"turndown-root\">' + input + '</x-turndown>',\n        'text/html'\n      );\n      root = doc.getElementById('turndown-root');\n    } else {\n      root = input.cloneNode(true);\n    }\n    collapseWhitespace({\n      element: root,\n      isBlock: isBlock,\n      isVoid: isVoid,\n      isPre: options.preformattedCode ? isPreOrCode : null\n    });\n\n    return root\n  }\n\n  var _htmlParser;\n  function htmlParser () {\n    _htmlParser = _htmlParser || new HTMLParser();\n    return _htmlParser\n  }\n\n  function isPreOrCode (node) {\n    return node.nodeName === 'PRE' || node.nodeName === 'CODE'\n  }\n\n  function Node (node, options) {\n    node.isBlock = isBlock(node);\n    node.isCode = node.nodeName === 'CODE' || node.parentNode.isCode;\n    node.isBlank = isBlank(node);\n    node.flankingWhitespace = flankingWhitespace(node, options);\n    return node\n  }\n\n  function isBlank (node) {\n    return (\n      !isVoid(node) &&\n      !isMeaningfulWhenBlank(node) &&\n      /^\\s*$/i.test(node.textContent) &&\n      !hasVoid(node) &&\n      !hasMeaningfulWhenBlank(node)\n    )\n  }\n\n  function flankingWhitespace (node, options) {\n    if (node.isBlock || (options.preformattedCode && node.isCode)) {\n      return { leading: '', trailing: '' }\n    }\n\n    var edges = edgeWhitespace(node.textContent);\n\n    // abandon leading ASCII WS if left-flanked by ASCII WS\n    if (edges.leadingAscii && isFlankedByWhitespace('left', node, options)) {\n      edges.leading = edges.leadingNonAscii;\n    }\n\n    // abandon trailing ASCII WS if right-flanked by ASCII WS\n    if (edges.trailingAscii && isFlankedByWhitespace('right', node, options)) {\n      edges.trailing = edges.trailingNonAscii;\n    }\n\n    return { leading: edges.leading, trailing: edges.trailing }\n  }\n\n  function edgeWhitespace (string) {\n    var m = string.match(/^(([ \\t\\r\\n]*)(\\s*))(?:(?=\\S)[\\s\\S]*\\S)?((\\s*?)([ \\t\\r\\n]*))$/);\n    return {\n      leading: m[1], // whole string for whitespace-only strings\n      leadingAscii: m[2],\n      leadingNonAscii: m[3],\n      trailing: m[4], // empty for whitespace-only strings\n      trailingNonAscii: m[5],\n      trailingAscii: m[6]\n    }\n  }\n\n  function isFlankedByWhitespace (side, node, options) {\n    var sibling;\n    var regExp;\n    var isFlanked;\n\n    if (side === 'left') {\n      sibling = node.previousSibling;\n      regExp = / $/;\n    } else {\n      sibling = node.nextSibling;\n      regExp = /^ /;\n    }\n\n    if (sibling) {\n      if (sibling.nodeType === 3) {\n        isFlanked = regExp.test(sibling.nodeValue);\n      } else if (options.preformattedCode && sibling.nodeName === 'CODE') {\n        isFlanked = false;\n      } else if (sibling.nodeType === 1 && !isBlock(sibling)) {\n        isFlanked = regExp.test(sibling.textContent);\n      }\n    }\n    return isFlanked\n  }\n\n  var reduce = Array.prototype.reduce;\n  var escapes = [\n    [/\\\\/g, '\\\\\\\\'],\n    [/\\*/g, '\\\\*'],\n    [/^-/g, '\\\\-'],\n    [/^\\+ /g, '\\\\+ '],\n    [/^(=+)/g, '\\\\$1'],\n    [/^(#{1,6}) /g, '\\\\$1 '],\n    [/`/g, '\\\\`'],\n    [/^~~~/g, '\\\\~~~'],\n    [/\\[/g, '\\\\['],\n    [/\\]/g, '\\\\]'],\n    [/^>/g, '\\\\>'],\n    [/_/g, '\\\\_'],\n    [/^(\\d+)\\. /g, '$1\\\\. ']\n  ];\n\n  function TurndownService (options) {\n    if (!(this instanceof TurndownService)) return new TurndownService(options)\n\n    var defaults = {\n      rules: rules,\n      headingStyle: 'setext',\n      hr: '* * *',\n      bulletListMarker: '*',\n      codeBlockStyle: 'indented',\n      fence: '```',\n      emDelimiter: '_',\n      strongDelimiter: '**',\n      linkStyle: 'inlined',\n      linkReferenceStyle: 'full',\n      br: '  ',\n      preformattedCode: false,\n      blankReplacement: function (content, node) {\n        return node.isBlock ? '\\n\\n' : ''\n      },\n      keepReplacement: function (content, node) {\n        return node.isBlock ? '\\n\\n' + node.outerHTML + '\\n\\n' : node.outerHTML\n      },\n      defaultReplacement: function (content, node) {\n        return node.isBlock ? '\\n\\n' + content + '\\n\\n' : content\n      }\n    };\n    this.options = extend({}, defaults, options);\n    this.rules = new Rules(this.options);\n  }\n\n  TurndownService.prototype = {\n    /**\n     * The entry point for converting a string or DOM node to Markdown\n     * @public\n     * @param {String|HTMLElement} input The string or DOM node to convert\n     * @returns A Markdown representation of the input\n     * @type String\n     */\n\n    turndown: function (input) {\n      if (!canConvert(input)) {\n        throw new TypeError(\n          input + ' is not a string, or an element/document/fragment node.'\n        )\n      }\n\n      if (input === '') return ''\n\n      var output = process.call(this, new RootNode(input, this.options));\n      return postProcess.call(this, output)\n    },\n\n    /**\n     * Add one or more plugins\n     * @public\n     * @param {Function|Array} plugin The plugin or array of plugins to add\n     * @returns The Turndown instance for chaining\n     * @type Object\n     */\n\n    use: function (plugin) {\n      if (Array.isArray(plugin)) {\n        for (var i = 0; i < plugin.length; i++) this.use(plugin[i]);\n      } else if (typeof plugin === 'function') {\n        plugin(this);\n      } else {\n        throw new TypeError('plugin must be a Function or an Array of Functions')\n      }\n      return this\n    },\n\n    /**\n     * Adds a rule\n     * @public\n     * @param {String} key The unique key of the rule\n     * @param {Object} rule The rule\n     * @returns The Turndown instance for chaining\n     * @type Object\n     */\n\n    addRule: function (key, rule) {\n      this.rules.add(key, rule);\n      return this\n    },\n\n    /**\n     * Keep a node (as HTML) that matches the filter\n     * @public\n     * @param {String|Array|Function} filter The unique key of the rule\n     * @returns The Turndown instance for chaining\n     * @type Object\n     */\n\n    keep: function (filter) {\n      this.rules.keep(filter);\n      return this\n    },\n\n    /**\n     * Remove a node that matches the filter\n     * @public\n     * @param {String|Array|Function} filter The unique key of the rule\n     * @returns The Turndown instance for chaining\n     * @type Object\n     */\n\n    remove: function (filter) {\n      this.rules.remove(filter);\n      return this\n    },\n\n    /**\n     * Escapes Markdown syntax\n     * @public\n     * @param {String} string The string to escape\n     * @returns A string with Markdown syntax escaped\n     * @type String\n     */\n\n    escape: function (string) {\n      return escapes.reduce(function (accumulator, escape) {\n        return accumulator.replace(escape[0], escape[1])\n      }, string)\n    }\n  };\n\n  /**\n   * Reduces a DOM node down to its Markdown string equivalent\n   * @private\n   * @param {HTMLElement} parentNode The node to convert\n   * @returns A Markdown representation of the node\n   * @type String\n   */\n\n  function process (parentNode) {\n    var self = this;\n    return reduce.call(parentNode.childNodes, function (output, node) {\n      node = new Node(node, self.options);\n\n      var replacement = '';\n      if (node.nodeType === 3) {\n        replacement = node.isCode ? node.nodeValue : self.escape(node.nodeValue);\n      } else if (node.nodeType === 1) {\n        replacement = replacementForNode.call(self, node);\n      }\n\n      return join(output, replacement)\n    }, '')\n  }\n\n  /**\n   * Appends strings as each rule requires and trims the output\n   * @private\n   * @param {String} output The conversion output\n   * @returns A trimmed version of the ouput\n   * @type String\n   */\n\n  function postProcess (output) {\n    var self = this;\n    this.rules.forEach(function (rule) {\n      if (typeof rule.append === 'function') {\n        output = join(output, rule.append(self.options));\n      }\n    });\n\n    return output.replace(/^[\\t\\r\\n]+/, '').replace(/[\\t\\r\\n\\s]+$/, '')\n  }\n\n  /**\n   * Converts an element node to its Markdown equivalent\n   * @private\n   * @param {HTMLElement} node The node to convert\n   * @returns A Markdown representation of the node\n   * @type String\n   */\n\n  function replacementForNode (node) {\n    var rule = this.rules.forNode(node);\n    var content = process.call(this, node);\n    var whitespace = node.flankingWhitespace;\n    if (whitespace.leading || whitespace.trailing) content = content.trim();\n    return (\n      whitespace.leading +\n      rule.replacement(content, node, this.options) +\n      whitespace.trailing\n    )\n  }\n\n  /**\n   * Joins replacement to the current output with appropriate number of new lines\n   * @private\n   * @param {String} output The current conversion output\n   * @param {String} replacement The string to append to the output\n   * @returns Joined output\n   * @type String\n   */\n\n  function join (output, replacement) {\n    var s1 = trimTrailingNewlines(output);\n    var s2 = trimLeadingNewlines(replacement);\n    var nls = Math.max(output.length - s1.length, replacement.length - s2.length);\n    var separator = '\\n\\n'.substring(0, nls);\n\n    return s1 + separator + s2\n  }\n\n  /**\n   * Determines whether an input can be converted\n   * @private\n   * @param {String|HTMLElement} input Describe this parameter\n   * @returns Describe what it returns\n   * @type String|Object|Array|Boolean|Number\n   */\n\n  function canConvert (input) {\n    return (\n      input != null && (\n        typeof input === 'string' ||\n        (input.nodeType && (\n          input.nodeType === 1 || input.nodeType === 9 || input.nodeType === 11\n        ))\n      )\n    )\n  }\n\n  return TurndownService;\n\n}());\n";
  const getWebContentCdpSchema = {
    tabId: number$1().int().positive().describe("Target tab ID to fetch content from."),
    selector: string$1().optional().describe(
      "CSS selector to get HTML from a specific element. If not provided, gets entire page HTML (document.documentElement.outerHTML)."
    ),
    outputFormat: _enum$1(["html", "markdown", "both"]).optional().default("html").describe('Output format: "html" (default), "markdown", or "both".')
  };
  class GetWebContentToolCDP extends BaseBrowserToolExecutor {
    constructor() {
      super(...arguments);
      __publicField2(this, "name", TOOL_NAMES.BROWSER.WEB_FETCHER);
      __publicField2(this, "description", "Get HTML or Markdown content from existing tab using CDP and upload to object storage. Supports background execution (no tab activation), element-specific content via CSS selector, and multiple output formats (HTML, Markdown, or both). Always uploads to storage and returns access URL(s).");
      __publicField2(this, "annotations", {
        title: "Get Web Content (CDP)",
        category: ToolCategory.DEBUGGING,
        readOnlyHint: true
      });
      __publicField2(this, "schema", getWebContentCdpSchema);
    }
    execute(args) {
      return __async(this, null, function* () {
        console.log("[CDP 获取内容] 开始执行，参数:", args);
        const validationResult = this.validateArgs(args);
        if (!validationResult.success) {
          return validationResult.error;
        }
        const { tabId, selector, outputFormat = "html" } = validationResult.data;
        console.log("[CDP 获取内容] 使用现有 tab 的当前页面:", tabId);
        const targetTab = yield cdpDebuggerManager.getTargetTab(tabId, false);
        const targetTabId = targetTab.id;
        return yield cdpSessionExecutor.executeWithSession(targetTabId, (session, viewport) => __async(this, null, function* () {
          try {
            console.log(
              `[CDP 获取内容] 获取内容 (格式: ${outputFormat}), selector:`,
              selector || "document.documentElement"
            );
            let htmlContent;
            let markdownContent;
            if (outputFormat === "html") {
              htmlContent = yield this._getHtmlContent(session, selector);
            } else if (outputFormat === "markdown") {
              markdownContent = yield this._getMarkdownContent(session, selector);
            } else {
              [htmlContent, markdownContent] = yield Promise.all([
                this._getHtmlContent(session, selector),
                this._getMarkdownContent(session, selector)
              ]);
            }
            console.log(`[CDP 获取内容] 上传内容 (格式: ${outputFormat})`);
            return yield this._uploadContent(htmlContent, markdownContent, outputFormat, targetTab);
          } catch (err) {
            console.error("[CDP 获取内容] 错误:", err);
            return error$J(
              `获取内容失败: ${err instanceof Error ? err.message : String(err)}`,
              "EXECUTION_ERROR",
              {
                tab: targetTab,
                input: args,
                stack: err instanceof Error ? err.stack : void 0
              }
            );
          }
        }));
      });
    }
    /**
     * 获取原始 HTML 内容（不做任何清理）
     */
    _getHtmlContent(session, selector) {
      return __async(this, null, function* () {
        const expression = `
      (function() {
        const element = ${selector ? `document.querySelector(${JSON.stringify(selector)})` : "document.documentElement"};

        if (!element) {
          return { error: 'Element not found', selector: ${JSON.stringify(selector)} };
        }

        return element.outerHTML;
      })()
    `;
        const result2 = yield session.send("Runtime.evaluate", {
          expression,
          returnByValue: true,
          awaitPromise: false
        });
        if (result2.exceptionDetails) {
          throw new Error(
            `JavaScript execution error: ${result2.exceptionDetails.text || "Unknown error"}`
          );
        }
        const value = result2.result.value;
        if (value && typeof value === "object" && value.error) {
          throw new Error(`${value.error}${value.selector ? ` (selector: ${value.selector})` : ""}`);
        }
        if (typeof value !== "string") {
          throw new Error(`Unexpected return type: expected string, got ${typeof value}`);
        }
        return value;
      });
    }
    /**
     * 通过 CDP 注入 Turndown 并转换为 Markdown
     */
    _getMarkdownContent(session, selector) {
      return __async(this, null, function* () {
        const conversionScript = `
      ${turndownJs}

      // Turndown 配置
      (function() {
        const service = new TurndownService({
          headingStyle: 'atx',
          hr: '---',
          bulletListMarker: '-',
          codeBlockStyle: 'fenced',
          fence: '\`\`\`',
          emDelimiter: '_',
          strongDelimiter: '**',
          linkStyle: 'inlined',
        });

        // 自定义规则：链接 URL 移除
        // service.addRule('customLinks', {
        //   filter: 'a',
        //   replacement: function(content, node) {
        //     if (!content.trim()) return '';

        //     // 完全移除 URL，减少 token
        //     return '[' + content + ']()';
        //   }
        // });

        // 自定义规则:移除 base64 编码的图片
        service.addRule('customImages', {
          filter: 'img',
          replacement: function(content, node) {
            const src = node.getAttribute('src') || '';
            
            // 如果是 base64 编码的图片,完全移除
            if (src.startsWith('data:')) {
              return '';
            }
            
            // 普通 URL 图片保留为文本占位符
            const alt = node.getAttribute('alt') || '';
            const imageText = alt ? '[Image: ' + alt + ']' : '[Image]';
            return imageText + '('+ src +')';
          }
        });

        // 自定义规则：表格内换行
        service.addRule('tableLineBreaks', {
          filter: 'br',
          replacement: function(content, node) {
            const inTableCell = node.closest('td') || node.closest('th');
            return inTableCell ? ' ' : '  \\n';
          }
        });

        // 移除脚本和样式
        service.remove(['script', 'style', 'noscript', 'iframe']);

        // 获取目标元素
        const element = ${selector ? `document.querySelector(${JSON.stringify(selector)})` : "document.documentElement"};

        if (!element) {
          return { error: 'Element not found', selector: ${JSON.stringify(selector)} };
        }

        // 执行转换
        try {
          const markdown = service.turndown(element.outerHTML);

          // 清理多余空行
          return markdown.replace(/\\n{3,}/g, '\\n\\n').trim();
        } catch (err) {
          return { error: 'Conversion failed', message: err.message };
        }
      })()
    `;
        const result2 = yield session.send("Runtime.evaluate", {
          expression: conversionScript,
          returnByValue: true,
          awaitPromise: false
        });
        if (result2.exceptionDetails) {
          throw new Error(
            `Turndown execution error: ${result2.exceptionDetails.text || "Unknown error"}`
          );
        }
        const value = result2.result.value;
        if (value && typeof value === "object" && value.error) {
          throw new Error(`${value.error}${value.message ? `: ${value.message}` : ""}`);
        }
        if (typeof value !== "string") {
          throw new Error(`Unexpected return type: expected string, got ${typeof value}`);
        }
        return value;
      });
    }
    /**
     * 生成文件名基础信息
     */
    _generateFileName(tab) {
      let domainName = "webpage";
      try {
        const url2 = new URL(tab.url || "");
        domainName = url2.hostname.replace(/^www\./, "").replace(/\./g, "_");
      } catch (e) {
        console.warn("[CDP 获取内容] 无法解析 URL:", e);
      }
      const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").substring(0, 19);
      return { baseName: domainName, timestamp };
    }
    /**
     * 上传单个文件到 OSS
     */
    _uploadSingleFile(content, filename, mimeType) {
      return __async(this, null, function* () {
        const file2 = new File([content], filename, { type: mimeType });
        console.log(`[CDP 获取内容] 上传文件: ${filename}, 大小: ${file2.size} bytes`);
        const uploadResult = yield uploadFile$1(file2, {
          filename,
          purpose: "external_resource"
        });
        if (!uploadResult.success) {
          throw new Error(`上传失败: ${uploadResult.error}`);
        }
        return {
          objectKey: uploadResult.objectKey,
          url: uploadResult.url,
          size: file2.size
        };
      });
    }
    /**
     * 根据 outputFormat 上传内容并返回结果
     */
    _uploadContent(htmlContent, markdownContent, outputFormat, tab) {
      return __async(this, null, function* () {
        try {
          const { baseName, timestamp } = this._generateFileName(tab);
          if (outputFormat === "html" && htmlContent) {
            const result2 = yield this._uploadSingleFile(
              htmlContent,
              `${baseName}_${timestamp}.html`,
              "text/html"
            );
            return success$1(`HTML content uploaded: ${result2.url}`, {
              tabId: tab.id,
              url: tab.url,
              title: tab.title,
              format: "html",
              contentSize: result2.size
            });
          } else if (outputFormat === "markdown" && markdownContent) {
            const result2 = yield this._uploadSingleFile(
              markdownContent,
              `${baseName}_${timestamp}.txt`,
              "text/plain"
            );
            return success$1(`Markdown content uploaded: ${result2.url}`, {
              tabId: tab.id,
              url: tab.url,
              title: tab.title,
              format: "markdown",
              contentSize: result2.size
            });
          } else if (outputFormat === "both" && htmlContent && markdownContent) {
            const [htmlResult, markdownResult] = yield Promise.all([
              this._uploadSingleFile(htmlContent, `${baseName}_${timestamp}.html`, "text/html"),
              this._uploadSingleFile(markdownContent, `${baseName}_${timestamp}.txt`, "text/plain")
            ]);
            const message = `Content uploaded in both formats:
- HTML: ${htmlResult.url}
- Markdown: ${markdownResult.url}`;
            return success$1(message, {
              tabId: tab.id,
              url: tab.url,
              title: tab.title,
              formats: {
                html: {
                  objectKey: htmlResult.objectKey,
                  url: htmlResult.url,
                  size: htmlResult.size
                },
                markdown: {
                  objectKey: markdownResult.objectKey,
                  url: markdownResult.url,
                  size: markdownResult.size
                }
              }
            });
          } else {
            throw new Error(`Invalid content state for format ${outputFormat}`);
          }
        } catch (err) {
          return error$J(
            `上传处理失败: ${err instanceof Error ? err.message : String(err)}`,
            "UPLOAD_ERROR",
            { stack: err instanceof Error ? err.stack : void 0 }
          );
        }
      });
    }
    /**
     * 等待页面加载完成事件
     */
    _waitForLoadEvent(tabId) {
      return __async(this, null, function* () {
        const timeout = 3e4;
        return new Promise((resolve2, reject) => {
          const timeoutId = setTimeout(() => {
            chrome.debugger.onEvent.removeListener(listener);
            reject(new Error(`Navigation timeout after ${timeout}ms`));
          }, timeout);
          const listener = (source, method) => {
            if (source.tabId === tabId && method === "Page.loadEventFired") {
              clearTimeout(timeoutId);
              chrome.debugger.onEvent.removeListener(listener);
              console.log("[CDP 获取内容] 收到 Page.loadEventFired 事件");
              resolve2();
            }
          };
          chrome.debugger.onEvent.addListener(listener);
        });
      });
    }
  }
  const getWebContentToolCDP = new GetWebContentToolCDP();
  class ImageProcessor {
    /**
     * 处理图片数据 URL
     * @param dataUrl 原始图片 data URL
     * @param options 处理选项
     * @returns 处理结果
     */
    process(dataUrl, options) {
      return __async(this, null, function* () {
        try {
          const compressionOptions = options.compression || {};
          const compressed = yield compressImage(dataUrl, {
            scale: compressionOptions.scale || 1,
            quality: compressionOptions.quality || 0.8,
            format: compressionOptions.format || "image/jpeg"
          });
          const imageBitmap = yield createImageBitmapFromUrl(compressed.dataUrl);
          const dimensions = {
            width: imageBitmap.width,
            height: imageBitmap.height
          };
          if (options.outputMode === "base64") {
            const base64Data = compressed.dataUrl.replace(/^data:image\/[^;]+;base64,/, "");
            return {
              success: true,
              base64: base64Data,
              mimeType: compressed.mimeType,
              dimensions
            };
          } else {
            if (!options.upload) {
              return {
                success: false,
                error: 'Upload options are required when outputMode is "upload"'
              };
            }
            const uploadResult = yield uploadFileFromUrl(
              compressed.dataUrl,
              options.upload.filename
            );
            if (!uploadResult.success) {
              return {
                success: false,
                error: uploadResult.error || "Upload failed"
              };
            }
            return {
              success: true,
              mimeType: compressed.mimeType,
              dimensions,
              upload: {
                objectKey: uploadResult.objectKey,
                url: uploadResult.url
              }
            };
          }
        } catch (error2) {
          return {
            success: false,
            error: error2 instanceof Error ? error2.message : String(error2)
          };
        }
      });
    }
    /**
     * 获取默认配置（用于不同场景）
     * @param scenario 场景：'base64' 或 'upload'
     * @returns 默认配置
     */
    static getDefaultOptions(scenario) {
      if (scenario === "base64") {
        return {
          outputMode: "base64",
          compression: {
            scale: 0.7,
            // 减小 30% 尺寸
            quality: 0.8,
            // 80% 质量
            format: "image/jpeg"
            // JPEG 压缩率更好
          }
        };
      } else {
        return {
          outputMode: "upload",
          compression: {
            scale: 0.8,
            // 减小 20% 尺寸
            quality: 0.85,
            // 85% 质量
            format: "image/webp"
            // WebP 压缩率和质量都好
          }
        };
      }
    }
  }
  const accessibilitySnapshotToolSchema = {
    tabId: number$1().int().min(1).optional().describe("Target tab ID (optional)")
    // uploadImage: zod
    //   .boolean()
    //   .default(false)
    //   .describe('Upload screenshot to server instead of returning base64'),
  };
  const EXCLUDED_TAGS = /* @__PURE__ */ new Set([
    "html",
    "head",
    "body",
    "svg",
    "script",
    "style",
    "link",
    "meta",
    "title",
    "base",
    "noscript"
  ]);
  const CLICKABLE_TAGS = /* @__PURE__ */ new Set([
    "a",
    "button",
    "input",
    "textarea",
    "select",
    "option",
    "label",
    "details",
    "summary"
  ]);
  const CLICKABLE_ROLES = /* @__PURE__ */ new Set([
    "button",
    "link",
    "checkbox",
    "radio",
    "textbox",
    "combobox",
    "listbox",
    "option",
    "menuitem",
    "menuitemcheckbox",
    "menuitemradio",
    "tab",
    "switch",
    "slider",
    "spinbutton",
    "searchbox",
    "treeitem"
  ]);
  function extractCSSStyles(strings, styleIndexes) {
    const styles = {};
    const STYLE_NAMES = ["display", "visibility", "opacity", "pointer-events"];
    for (let i2 = 0; i2 < styleIndexes.length && i2 < STYLE_NAMES.length; i2++) {
      const valueIndex = styleIndexes[i2];
      if (valueIndex >= 0 && valueIndex < strings.length) {
        styles[STYLE_NAMES[i2]] = strings[valueIndex];
      }
    }
    return styles;
  }
  function extractAttributes(attributeIndexes, strings) {
    if (!attributeIndexes) return {};
    const attributes = {};
    for (let i2 = 0; i2 < attributeIndexes.length; i2 += 2) {
      const nameIndex = attributeIndexes[i2];
      const valueIndex = attributeIndexes[i2 + 1];
      if (nameIndex >= 0 && nameIndex < strings.length) {
        const attrName = strings[nameIndex];
        const attrValue = valueIndex !== void 0 && valueIndex >= 0 && valueIndex < strings.length ? strings[valueIndex] : "";
        attributes[attrName] = attrValue;
      }
    }
    return attributes;
  }
  function checkIsClickable(isClickable, nodeIdx) {
    if (!isClickable || !isClickable.index) return false;
    return isClickable.index.includes(nodeIdx);
  }
  function isElementVisible(rect, styles) {
    if (rect.width <= 0.5 || rect.height <= 0.5) {
      return false;
    }
    if (styles.display === "none") {
      return false;
    }
    if (styles.visibility === "hidden" || styles.visibility === "collapse") {
      return false;
    }
    if (styles.opacity === "0") {
      return false;
    }
    if (styles["pointer-events"] === "none") {
      return false;
    }
    return true;
  }
  function isElementClickable(tagName, isClickableFlag, attributes) {
    var _a3;
    if (EXCLUDED_TAGS.has(tagName)) {
      return false;
    }
    if (isClickableFlag || CLICKABLE_TAGS.has(tagName) || attributes.contenteditable === "true") {
      return true;
    }
    const role = (_a3 = attributes.role) == null ? void 0 : _a3.toLowerCase();
    if (role && CLICKABLE_ROLES.has(role)) {
      return true;
    }
    if (attributes.tabindex !== void 0 && attributes.tabindex !== "-1") {
      return true;
    }
    return false;
  }
  function extractCandidates(snapshot, devicePixelRatio) {
    const candidates = [];
    const { strings, documents } = snapshot;
    if (!(strings == null ? void 0 : strings.length) || !(documents == null ? void 0 : documents.length)) {
      console.warn("[CDP Snapshot] 快照数据为空");
      return candidates;
    }
    for (const doc of documents) {
      const { nodes, layout } = doc;
      if (!nodes || !layout) continue;
      const { backendNodeId, nodeType, nodeName, attributes, isClickable } = nodes;
      const { nodeIndex, bounds, styles, paintOrders } = layout;
      const nodeIndexToLayoutIndex = /* @__PURE__ */ new Map();
      for (let i2 = 0; i2 < nodeIndex.length; i2++) {
        const idx = nodeIndex[i2];
        if (!nodeIndexToLayoutIndex.has(idx)) {
          nodeIndexToLayoutIndex.set(idx, i2);
        }
      }
      console.log(
        `[CDP Snapshot] 处理文档: ${backendNodeId.length} 个节点, ${nodeIndex.length} 个布局`
      );
      for (let i2 = 0; i2 < backendNodeId.length; i2++) {
        if (nodeType[i2] !== 1) continue;
        const nameIndex = nodeName[i2];
        if (nameIndex < 0 || nameIndex >= strings.length) continue;
        const tagName = strings[nameIndex].toLowerCase();
        const layoutIndex = nodeIndexToLayoutIndex.get(i2);
        if (layoutIndex === void 0) continue;
        const rect = bounds[layoutIndex];
        if (!rect || rect.length < 4) continue;
        const [physicalX, physicalY, physicalWidth, physicalHeight] = rect;
        const cssRect = {
          x: physicalX / devicePixelRatio,
          y: physicalY / devicePixelRatio,
          width: physicalWidth / devicePixelRatio,
          height: physicalHeight / devicePixelRatio
        };
        const styleIndexes = (styles == null ? void 0 : styles[layoutIndex]) || [];
        const cssStyles = extractCSSStyles(strings, styleIndexes);
        if (!isElementVisible(cssRect, cssStyles)) {
          continue;
        }
        const attrIndexes = attributes[i2];
        const attrs = extractAttributes(attrIndexes, strings);
        const elementId = attrs.id || "";
        if (elementId.startsWith("mcp-") || elementId.startsWith("chrome-mcp-")) {
          continue;
        }
        const isClickableFlag = checkIsClickable(isClickable, i2);
        const elementIsClickable = isElementClickable(tagName, isClickableFlag, attrs);
        if (!elementIsClickable) {
          continue;
        }
        let paintOrder = null;
        if (paintOrders && layoutIndex < paintOrders.length) {
          paintOrder = paintOrders[layoutIndex];
        }
        candidates.push({
          backendNodeId: backendNodeId[i2],
          paintOrder,
          yPosition: cssRect.y,
          xPosition: cssRect.x,
          tagName,
          id: "",
          // 稍后分配 UID
          rect: cssRect,
          cssStyles,
          attributes: attrs,
          isClickable: elementIsClickable,
          isVisible: true
        });
      }
    }
    console.log(`[CDP Snapshot] 提取了 ${candidates.length} 个候选元素`);
    return candidates;
  }
  function sortCandidates(candidates) {
    return [...candidates].sort((a, b) => {
      const aPaintOrderPriority = a.paintOrder !== null ? 0 : 1;
      const bPaintOrderPriority = b.paintOrder !== null ? 0 : 1;
      if (aPaintOrderPriority !== bPaintOrderPriority) {
        return aPaintOrderPriority - bPaintOrderPriority;
      }
      if (a.paintOrder !== null && b.paintOrder !== null && a.paintOrder !== b.paintOrder) {
        return a.paintOrder - b.paintOrder;
      }
      if (a.yPosition !== b.yPosition) {
        return a.yPosition - b.yPosition;
      }
      return a.xPosition - b.xPosition;
    });
  }
  class AccessibilitySnapshotTool extends BaseBrowserToolExecutor {
    constructor() {
      super(...arguments);
      __publicField2(this, "name", TOOL_NAMES.BROWSER.ACCESSIBILITY_SNAPSHOT);
      __publicField2(this, "description", "⚠️ PRIMARY TOOL for element analysis - ALWAYS use this FIRST before chrome_get_interactive_elements. Capture clickable elements using CDP DOMSnapshot. Returns a flat list of interactive elements sorted by paint order and position. Each element includes coordinates, styles, and attributes. Use this tool to find elements to interact with on the page.");
      __publicField2(this, "annotations", {
        title: "Capture Accessibility Snapshot",
        category: ToolCategory.DEBUGGING,
        readOnlyHint: true
      });
      __publicField2(this, "schema", accessibilitySnapshotToolSchema);
      // 快照计数器
      __publicField2(this, "snapshotCounter", 1);
      // 当前快照缓存
      __publicField2(this, "currentSnapshot", null);
    }
    /**
     * 执行快照捕获（完整版：Markdown + 元素列表 + 截图）
     */
    execute(args) {
      return __async(this, null, function* () {
        var _a3, _b2, _c2, _d2, _e;
        console.log("[CDP Snapshot] 开始执行，参数:", args);
        const validationResult = this.validateArgs(args);
        if (!validationResult.success) {
          return validationResult.error;
        }
        const { tabId, uploadImage } = validationResult.data;
        let targetTab;
        try {
          console.log("[CDP Snapshot] 尝试获取 tab:", tabId);
          targetTab = yield cdpDebuggerManager.getTargetTab(tabId, false);
          const targetTabId = targetTab.id;
          console.log("[CDP Snapshot] 成功获取 tab:", targetTabId, targetTab.url);
          if (((_a3 = targetTab.url) == null ? void 0 : _a3.startsWith("chrome://")) || ((_b2 = targetTab.url) == null ? void 0 : _b2.startsWith("edge://")) || ((_c2 = targetTab.url) == null ? void 0 : _c2.startsWith("https://chrome.google.com/webstore")) || ((_d2 = targetTab.url) == null ? void 0 : _d2.startsWith("https://microsoftedge.microsoft.com/")) || ((_e = targetTab.url) == null ? void 0 : _e.includes("chrome-extension://"))) {
            return error$J(
              "Cannot capture snapshot from special browser pages, web store pages, or extension pages.",
              "EXECUTION_FAILED",
              {
                tab: targetTab,
                input: args
              }
            );
          }
          const result2 = yield cdpSessionExecutor.executeWithSession(
            targetTabId,
            (session, viewport) => __async(this, null, function* () {
              var _a4;
              const runtimeResult = yield session.send("Runtime.evaluate", {
                expression: "window.devicePixelRatio || 1",
                returnByValue: true
              });
              const devicePixelRatio = ((_a4 = runtimeResult.result) == null ? void 0 : _a4.value) || 1;
              const snapshot = yield this.captureSnapshot(session);
              console.log("[CDP Snapshot] 快照包含", snapshot.candidates.length, "个元素");
              let artifactData;
              try {
                artifactData = yield this.collectArtifactsFromContentScript(
                  targetTabId,
                  snapshot.snapshotId
                );
              } catch (err) {
                console.warn("[CDP Snapshot] Content Script 处理失败，回退到纯快照模式:", err);
                const formattedList = this.formatCandidates(snapshot.candidates);
                return success$1(formattedList, {
                  snapshotId: snapshot.snapshotId,
                  elementCount: snapshot.candidates.length,
                  mode: "snapshot-only"
                });
              }
              let screenshots;
              try {
                screenshots = yield this.captureWithHighlights(
                  session,
                  artifactData.elements || [],
                  devicePixelRatio
                );
              } catch (err) {
                console.warn("[CDP Snapshot] 截图失败:", err);
                screenshots = null;
              }
              return this.buildArtifactResult(
                artifactData.markdownContent,
                artifactData.elements,
                screenshots,
                // ← 跳过截图
                snapshot.snapshotId
              );
            })
          );
          return result2;
        } catch (err) {
          console.error("[CDP Snapshot] 错误:", err);
          return error$J(
            `快照捕获失败: ${err instanceof Error ? err.message : String(err)}`,
            "EXECUTION_FAILED",
            {
              tab: targetTab,
              input: args,
              stack: err instanceof Error ? err.stack : void 0
            }
          );
        }
      });
    }
    /**
     * 构建完整的 Artifact 结果
     */
    buildArtifactResult(markdownContent, elements, screenshots, snapshotId) {
      return __async(this, null, function* () {
        var _a3, _b2, _c2;
        const content = markdownContent;
        if (screenshots == null ? void 0 : screenshots.clean) {
          console.log("[CDP Snapshot] 处理图片");
          const dataUrl = `data:image/png;base64,${screenshots.clean.split(",")[1]}`;
          const outputMode = IMAGE_TYPE;
          const processOptions = ImageProcessor.getDefaultOptions(outputMode);
          const processor = new ImageProcessor();
          const processResult = yield processor.process(dataUrl, processOptions);
          if (!processResult.success) {
            throw new Error(processResult.error || "Image processing failed");
          }
          {
            return multiContent(
              [
                { type: "text", text: content },
                { type: "image", data: processResult.base64, mimeType: processResult.mimeType }
              ],
              {
                snapshotId,
                elementCount: elements.length,
                screenshot: {
                  format: (_a3 = processResult.mimeType) == null ? void 0 : _a3.split("/")[1],
                  width: (_b2 = processResult.dimensions) == null ? void 0 : _b2.width,
                  height: (_c2 = processResult.dimensions) == null ? void 0 : _c2.height
                }
              }
            );
          }
        }
        return multiContent([{ type: "text", text: content }], {
          snapshotId,
          elementCount: elements.length,
          // 移除 elements 重复数据 - 坐标信息已包含在 Markdown 文本中
          hasScreenshots: !!screenshots,
          timestamp: Date.now()
        });
      });
    }
    /**
     * 捕获快照（Manus 方式）
     */
    captureSnapshot(session) {
      return __async(this, null, function* () {
        var _a3;
        yield session.send("DOM.enable", {});
        yield session.send("CSS.enable", {});
        try {
          try {
            yield session.send("DOM.getDocument", { depth: 0, pierce: true });
          } catch (error2) {
            console.warn("[CDP Snapshot] DOM 预热失败:", error2);
          }
          const runtimeResult = yield session.send("Runtime.evaluate", {
            expression: "window.devicePixelRatio || 1",
            returnByValue: true
          });
          const devicePixelRatio = ((_a3 = runtimeResult.result) == null ? void 0 : _a3.value) || 1;
          console.log(`[CDP Snapshot] 设备像素比 (DPR): ${devicePixelRatio}`);
          console.log("[CDP Snapshot] 开始捕获 DOMSnapshot");
          const snapshot = yield session.send("DOMSnapshot.captureSnapshot", {
            computedStyles: ["display", "visibility", "opacity", "pointer-events"],
            includeDOMRects: true,
            includePaintOrder: true
          });
          console.log("[CDP Snapshot] 快照获取成功");
          const candidates = extractCandidates(snapshot, devicePixelRatio);
          const sorted = sortCandidates(candidates);
          const snapshotId = this.snapshotCounter++;
          const idToCandidate = /* @__PURE__ */ new Map();
          const backendNodeIds = sorted.map((c) => c.backendNodeId);
          if (backendNodeIds.length > 0) {
            const pushResult = yield session.send("DOM.pushNodesByBackendIdsToFrontend", {
              backendNodeIds
            });
            const nodeIds = pushResult.nodeIds || [];
            console.log(`[CDP Snapshot] 开始标记 ${sorted.length} 个元素`);
            for (let i2 = 0; i2 < sorted.length; i2++) {
              const candidate = sorted[i2];
              const nodeId = nodeIds[i2];
              candidate.id = `${snapshotId}_${i2}`;
              idToCandidate.set(candidate.id, candidate);
              if (nodeId >= 0) {
                try {
                  yield session.send("DOM.setAttributeValue", {
                    nodeId,
                    name: "data-snapshot-uid",
                    value: candidate.id
                  });
                } catch (error2) {
                  console.warn(`[CDP Snapshot] 标记元素失败 ${candidate.id}:`, error2);
                }
              }
            }
            console.log("[CDP Snapshot] 元素标记完成");
          }
          this.currentSnapshot = {
            candidates: sorted,
            snapshotId: String(snapshotId),
            idToCandidate
          };
          return this.currentSnapshot;
        } finally {
          yield session.send("CSS.disable", {});
          yield session.send("DOM.disable", {});
        }
      });
    }
    /**
     * 格式化候选元素列表
     */
    formatCandidates(candidates) {
      if (candidates.length === 0) {
        return "# 可点击元素列表\n\n未找到任何可点击元素。";
      }
      const lines = ["# 可点击元素列表\n"];
      for (const candidate of candidates) {
        const attributes = [`uid=${candidate.id}`];
        attributes.push(candidate.tagName);
        const centerX = Math.round(candidate.rect.x + candidate.rect.width / 2);
        const centerY = Math.round(candidate.rect.y + candidate.rect.height / 2);
        attributes.push(`click=[${centerX},${centerY}]`);
        attributes.push(
          `bounds=[${Math.round(candidate.rect.x)},${Math.round(candidate.rect.y)},${Math.round(candidate.rect.width)},${Math.round(candidate.rect.height)}]`
        );
        if (candidate.paintOrder !== null) {
          attributes.push(`z=${candidate.paintOrder}`);
        }
        if (candidate.attributes.id) {
          attributes.push(`id="${candidate.attributes.id}"`);
        }
        if (candidate.attributes.class) {
          attributes.push(`class="${candidate.attributes.class}"`);
        }
        if (candidate.attributes.type) {
          attributes.push(`type="${candidate.attributes.type}"`);
        }
        if (candidate.attributes.role) {
          attributes.push(`role="${candidate.attributes.role}"`);
        }
        if (candidate.attributes["aria-label"]) {
          attributes.push(`aria-label="${candidate.attributes["aria-label"]}"`);
        }
        if (candidate.attributes.placeholder) {
          attributes.push(`placeholder="${candidate.attributes.placeholder}"`);
        }
        if (candidate.attributes.value) {
          attributes.push(`value="${candidate.attributes.value}"`);
        }
        if (candidate.attributes.href) {
          attributes.push(`href="${candidate.attributes.href}"`);
        }
        if (candidate.attributes.title) {
          attributes.push(`title="${candidate.attributes.title}"`);
        }
        if (candidate.attributes.disabled === "") {
          attributes.push("disabled");
        }
        lines.push(attributes.join(" "));
      }
      return lines.join("\n");
    }
    /**
     * 通过 UID 获取候选元素（供其他工具使用）
     */
    getCandidateByUid(uid) {
      if (!this.currentSnapshot) {
        throw new Error("No snapshot available. Please capture a snapshot first.");
      }
      const [snapshotId] = uid.split("_");
      if (this.currentSnapshot.snapshotId !== snapshotId) {
        throw new Error("Stale UID. Please capture a new snapshot.");
      }
      const candidate = this.currentSnapshot.idToCandidate.get(uid);
      if (candidate) {
        console.log(`[CDP Snapshot] 找到元素 UID "${uid}":`, {
          tagName: candidate.tagName,
          id: candidate.attributes.id,
          backendNodeId: candidate.backendNodeId
        });
      } else {
        console.warn(`[CDP Snapshot] 未找到元素 UID "${uid}"`);
      }
      return candidate || null;
    }
    /**
     * 获取当前快照（供其他工具使用）
     */
    getCurrentSnapshot() {
      return this.currentSnapshot;
    }
    /**
     * 从 Content Script 收集数据（Turndown 在页面上下文中运行）
     * Manus 优化：添加注入检测，避免重复注入
     */
    collectArtifactsFromContentScript(tabId, snapshotId, timeout = 5e3) {
      return __async(this, null, function* () {
        var _a3, _b2;
        console.log(`[CDP Snapshot] 调用 Content Script 收集数据，tabId: ${tabId}`);
        try {
          const checkResults = yield chrome.scripting.executeScript({
            target: { tabId },
            func: () => !!window.__collectSnapshotArtifacts
          });
          const isInjected = (_a3 = checkResults[0]) == null ? void 0 : _a3.result;
          if (!isInjected) {
            console.log("[CDP Snapshot] 注入 Content Script (~38KB)");
            yield chrome.scripting.executeScript({
              target: { tabId },
              files: ["/content-scripts/snapshot-helper.js"]
            });
          } else {
            console.log("[CDP Snapshot] Content Script 已注入，跳过注入");
          }
          const results = yield chrome.scripting.executeScript({
            target: { tabId },
            func: () => {
              return window.__collectSnapshotArtifacts();
            }
          });
          if (!results || results.length === 0) {
            throw new Error("Content Script 未返回结果");
          }
          const response = results[0].result;
          if (!response) {
            throw new Error("Content Script 返回值为空");
          }
          if (!response.ok) {
            throw new Error(response.error || "Content Script 处理失败");
          }
          console.log(`[CDP Snapshot] Content Script 执行成功，elements: ${(_b2 = response.elements) == null ? void 0 : _b2.length}`);
          return response;
        } catch (error2) {
          console.error("[CDP Snapshot] Content Script 执行失败:", error2);
          throw error2;
        }
      });
    }
    /**
     * 截图并绘制高亮
     */
    captureWithHighlights(session, elements, devicePixelRatio) {
      return __async(this, null, function* () {
        console.log("[CDP Snapshot] 开始截图");
        const screenshotResult = yield session.send("Page.captureScreenshot", {
          format: "png",
          fromSurface: true,
          captureBeyondViewport: false
        });
        const cleanDataUrl = `data:image/png;base64,${screenshotResult.data}`;
        console.log("[CDP Snapshot] 干净截图完成");
        return {
          clean: cleanDataUrl
          // highlighted: highlightedDataUrl,
        };
      });
    }
    /**
     * 在截图上绘制元素高亮
     */
    drawHighlights(screenshotDataUrl, elements, devicePixelRatio) {
      return __async(this, null, function* () {
        const response = yield fetch(screenshotDataUrl);
        const blob = yield response.blob();
        const imageBitmap = yield createImageBitmap(blob);
        console.log(`[CDP Snapshot] 图片尺寸: ${imageBitmap.width}x${imageBitmap.height}`);
        const canvas = new OffscreenCanvas(imageBitmap.width, imageBitmap.height);
        const ctx = canvas.getContext("2d");
        if (!ctx) {
          throw new Error("无法创建 Canvas 上下文");
        }
        ctx.drawImage(imageBitmap, 0, 0);
        for (const element of elements) {
          this.drawHighlightRect(ctx, element, devicePixelRatio, imageBitmap.width, imageBitmap.height);
        }
        imageBitmap.close();
        const resultBlob = yield canvas.convertToBlob({ type: "image/png" });
        const reader = new FileReader();
        return new Promise((resolve2, reject) => {
          reader.onloadend = () => {
            if (reader.result) {
              resolve2(reader.result);
            } else {
              reject(new Error("转换为 DataURL 失败"));
            }
          };
          reader.onerror = reject;
          reader.readAsDataURL(resultBlob);
        });
      });
    }
    /**
     * 绘制单个元素的高亮框
     */
    drawHighlightRect(ctx, element, devicePixelRatio, canvasWidth, canvasHeight) {
      const { rect, index: index2, tagName } = element;
      const x = rect.x * devicePixelRatio;
      const y = rect.y * devicePixelRatio;
      const width = rect.width * devicePixelRatio;
      const height = rect.height * devicePixelRatio;
      const left = Math.max(0, Math.min(x, canvasWidth));
      const top = Math.max(0, Math.min(y, canvasHeight));
      const right = Math.max(0, Math.min(x + width, canvasWidth));
      const bottom = Math.max(0, Math.min(y + height, canvasHeight));
      if (right - left < 1 || bottom - top < 1) {
        return;
      }
      const color = this.getElementColor(tagName);
      this.drawDashedRect(ctx, left, top, right, bottom, color);
      this.drawLabel(ctx, index2, left, top, color, canvasWidth);
    }
    /**
     * 绘制虚线矩形
     */
    drawDashedRect(ctx, left, top, right, bottom, color) {
      ctx.strokeStyle = color;
      ctx.lineWidth = 2;
      ctx.setLineDash([4, 8]);
      ctx.beginPath();
      ctx.rect(left, top, right - left, bottom - top);
      ctx.stroke();
      ctx.setLineDash([]);
    }
    /**
     * 绘制索引标签
     */
    drawLabel(ctx, index2, x, y, color, canvasWidth) {
      const text = index2.toString();
      const fontSize = Math.max(12, Math.min(20, Math.round(canvasWidth * 0.01)));
      ctx.font = `bold ${fontSize}px sans-serif`;
      const textWidth = ctx.measureText(text).width;
      const padding = 4;
      const labelWidth = textWidth + padding * 2;
      const labelHeight = fontSize + padding * 2;
      const labelX = x;
      const labelY = Math.max(0, y - labelHeight);
      ctx.fillStyle = color;
      ctx.fillRect(labelX, labelY, labelWidth, labelHeight);
      ctx.strokeStyle = "white";
      ctx.lineWidth = 2;
      ctx.strokeRect(labelX, labelY, labelWidth, labelHeight);
      ctx.fillStyle = "white";
      ctx.textBaseline = "top";
      ctx.fillText(text, labelX + padding, labelY + padding);
    }
    /**
     * 根据标签名获取元素颜色
     */
    getElementColor(tagName) {
      const colors = {
        button: "#FF6B6B",
        input: "#4ECDC4",
        select: "#45B7D1",
        a: "#96CEB4",
        textarea: "#FF8C42",
        default: "#DDA0DD"
      };
      return colors[tagName] || colors.default;
    }
  }
  const accessibilitySnapshotTool = new AccessibilitySnapshotTool();
  function getBackendNodeIdByUid(uid) {
    try {
      const candidate = accessibilitySnapshotTool.getCandidateByUid(uid);
      if (!candidate) {
        return null;
      }
      return candidate.backendNodeId || null;
    } catch (error2) {
      console.error("[CDP Snapshot] Error getting backend node ID:", error2);
      return null;
    }
  }
  const clickToolSchema = {
    selector: string$1().optional().describe('CSS selector of the element to click. Example: "#submit-button", ".btn-primary"'),
    coordinates: object({
      x: number$1().optional().describe("X coordinate relative to viewport"),
      y: number$1().optional().describe("Y coordinate relative to viewport")
    }).optional().transform((val) => {
      if (!val || val.x === void 0 && val.y === void 0) {
        return void 0;
      }
      if (val.x === void 0 || val.y === void 0) {
        throw new Error("Both x and y coordinates must be provided");
      }
      return val;
    }).describe(
      "Click coordinates (alternative to selector). Must provide either selector, coordinates, or uid."
    ),
    uid: string$1().optional().describe(
      'Unique ID from accessibility tree snapshot (alternative to selector or coordinates). Get this from chrome_accessibility_snapshot_cdp tool. Example: "1_42"'
    ),
    clickCount: number$1().int().nonnegative().default(1).describe(
      "Number of clicks: 0 for hover (no click, just move to element), 1 for single click, 2 for double click. Default: 1"
    ),
    button: _enum$1(["left", "right", "middle"]).default("left").describe(
      'Mouse button to use for clicking. Options: "left", "right", "middle". Default: "left"'
    ),
    waitForNavigation: boolean$1().default(false).describe(
      "Whether to wait for navigation after click. Set to true if the click triggers page navigation. Default: false"
    ),
    timeout: number$1().positive().default(TIMEOUTS.DEFAULT_WAIT * 5).describe(`Maximum time to wait in milliseconds. Default: ${TIMEOUTS.DEFAULT_WAIT * 5}ms`),
    tabId: number$1().int().positive().optional().describe("Target tab ID. If not provided, uses the currently active tab.")
  };
  class ClickTool extends BaseBrowserToolExecutor {
    constructor() {
      super(...arguments);
      __publicField2(this, "name", TOOL_NAMES.BROWSER.CLICK);
      __publicField2(this, "description", "**RECOMMENDED for element interaction** - Clicks on or hovers over elements using three methods: 1) UID from accessibility_snapshot (MOST RELIABLE - use this first), 2) CSS selector (with auto-scroll), or 3) coordinates. Supports hover (clickCount=0), single/double clicks, different mouse buttons, and navigation waiting. This CDP-powered tool is more reliable and powerful than standard click tools. For best results, use chrome_accessibility_snapshot_cdp first to get UIDs, then click using the uid parameter. IMPORTANT: If page protection is enabled, you MUST disable it first using chrome_page_protection_disable, otherwise clicks will be blocked and have no effect.");
      __publicField2(this, "annotations", {
        title: "Click Element",
        category: ToolCategory.INPUT,
        readOnlyHint: false
      });
      __publicField2(this, "schema", clickToolSchema);
    }
    /**
     * 执行点击操作
     * 通过 CDP 协议发送鼠标事件来实现页面元素点击
     */
    execute(args) {
      return __async(this, null, function* () {
        console.log(`开始执行 CDP 点击操作，原始参数:`, args);
        const validationResult = this.validateArgs(args);
        if (!validationResult.success) {
          return validationResult.error;
        }
        const { selector, coordinates, uid, waitForNavigation, timeout, tabId, button, clickCount } = validationResult.data;
        console.log(`参数验证通过，处理后的参数:`, validationResult.data);
        if (!selector && !coordinates && !uid) {
          return error$J(
            'Must provide selector, coordinates, or uid\n\nExamples:\n1. { "selector": "#submit-btn" }\n2. { "coordinates": { "x": 100, "y": 200 } }\n3. { "uid": "1_42" }',
            "INVALID_PARAMETERS"
          );
        }
        try {
          const targetTab = yield cdpDebuggerManager.getTargetTab(tabId);
          const targetTabId = targetTab.id;
          return yield cdpSessionExecutor.executeWithSession(targetTabId, (session, viewport) => __async(this, null, function* () {
            var _a3, _b2;
            let clickX = (_a3 = coordinates == null ? void 0 : coordinates.x) != null ? _a3 : 0;
            let clickY = (_b2 = coordinates == null ? void 0 : coordinates.y) != null ? _b2 : 0;
            let elementInfo = null;
            if (uid) {
              try {
                const backendNodeId = getBackendNodeIdByUid(uid);
                if (!backendNodeId) {
                  return error$J(
                    `Element not found for UID "${uid}"

Suggestion: Use chrome_accessibility_snapshot_cdp first to get valid UIDs`,
                    "ELEMENT_NOT_FOUND",
                    { uid }
                  );
                }
                console.log(`[CDP 点击] 通过 UID "${uid}" 获取到 backendNodeId: ${backendNodeId}`);
                console.log(`[CDP 点击] 检查元素是否需要滚动到可见位置`);
                yield cdpScrollHelper.scrollElementByBackendNodeIdToCenter(targetTabId, backendNodeId);
                const elementPosition = yield cdpElementHelper.getElementByBackendNodeId(
                  targetTabId,
                  backendNodeId
                );
                if ("error" in elementPosition) {
                  return error$J(
                    `Cannot get element position: ${elementPosition.error}`,
                    "ELEMENT_NOT_FOUND",
                    { uid, backendNodeId }
                  );
                }
                clickX = elementPosition.centerX;
                clickY = elementPosition.centerY;
                console.log(`[CDP 点击] UID 元素最终位置:`, {
                  clickX,
                  clickY,
                  rect: elementPosition.rect
                });
                elementInfo = {
                  clickMethod: "uid",
                  uid,
                  backendNodeId,
                  centerX: clickX,
                  centerY: clickY,
                  rect: elementPosition.rect
                };
              } catch (err) {
                console.error("通过 UID 获取元素信息失败:", err);
                return error$J(
                  `Failed to get element by UID: ${err instanceof Error ? err.message : String(err)}`,
                  "EXECUTION_FAILED",
                  { uid }
                );
              }
            } else if (selector) {
              try {
                const initialElementInfo = yield cdpElementHelper.findElement(targetTabId, selector, {
                  includeAbsolutePosition: true,
                  includeViewport: true,
                  includeScroll: true
                });
                if (initialElementInfo.error) {
                  return error$J(
                    `Element error: ${initialElementInfo.error}`,
                    initialElementInfo.error.includes("not visible") ? "ELEMENT_NOT_VISIBLE" : "ELEMENT_NOT_FOUND",
                    { selector }
                  );
                }
                console.log("[CDP 点击] 元素初始信息:", initialElementInfo);
                yield cdpScrollHelper.scrollElementToCenter(targetTabId, selector);
                elementInfo = yield cdpElementHelper.findElement(targetTabId, selector, {
                  includeAbsolutePosition: false,
                  includeViewport: false,
                  includeScroll: false
                });
                if (elementInfo.error) {
                  return error$J(
                    `Element error after scroll: ${elementInfo.error}`,
                    "ELEMENT_NOT_FOUND",
                    {
                      selector
                    }
                  );
                }
                clickX = elementInfo.centerX;
                clickY = elementInfo.centerY;
                console.log("[CDP 点击] 最终点击位置:", { clickX, clickY });
              } catch (err) {
                console.error("通过 CDP 获取元素信息失败:", err);
                return error$J(
                  `Failed to get element info: ${err instanceof Error ? err.message : String(err)}`,
                  "EXECUTION_FAILED",
                  { selector }
                );
              }
            } else if (coordinates) {
              try {
                elementInfo = yield cdpElementHelper.getElementAtPoint(targetTabId, clickX, clickY);
              } catch (error2) {
                console.warn("获取坐标位置元素信息失败:", error2);
                elementInfo = {
                  clickMethod: "coordinates",
                  clickPosition: { x: clickX, y: clickY }
                };
              }
            }
            yield cdpHighlighter.highlightClick(targetTabId, clickX, clickY);
            console.log("[CDP 点击] 执行点击事件:", {
              clickX,
              clickY,
              button,
              clickCount,
              selector,
              coordinates
            });
            const buttonMap = {
              left: "left",
              right: "right",
              middle: "middle"
            };
            yield session.send("Input.dispatchMouseEvent", {
              type: "mousePressed",
              x: clickX,
              y: clickY,
              button: buttonMap[button],
              clickCount
            });
            console.log("[CDP 点击] 鼠标按下事件已发送");
            yield new Promise((resolve2) => setTimeout(resolve2, 50));
            yield session.send("Input.dispatchMouseEvent", {
              type: "mouseReleased",
              x: clickX,
              y: clickY,
              button: buttonMap[button],
              clickCount
            });
            console.log("[CDP 点击] 鼠标释放事件已发送");
            if (waitForNavigation) {
              try {
                yield session.send("Page.enable", {});
                yield new Promise((resolve2) => {
                  const timer = setTimeout(() => {
                    chrome.debugger.onEvent.removeListener(listener);
                    resolve2(false);
                  }, timeout);
                  const listener = (source, method) => {
                    if (source.tabId === targetTabId && method === "Page.frameNavigated") {
                      clearTimeout(timer);
                      chrome.debugger.onEvent.removeListener(listener);
                      resolve2(true);
                    }
                  };
                  chrome.debugger.onEvent.addListener(listener);
                });
              } catch (error2) {
                console.warn("等待导航超时或失败:", error2);
              }
            }
            const action = clickCount === 0 ? "Hovered" : "Clicked";
            return success$1(`${action} at (${clickX}, ${clickY})`, {
              method: uid ? "uid" : selector ? "selector" : "coordinates",
              position: { x: clickX, y: clickY },
              action: clickCount === 0 ? "hover" : "click"
            });
          }));
        } catch (err) {
          console.error("CDP 点击操作错误:", err);
          return error$J(
            `Click failed: ${err instanceof Error ? err.message : String(err)}`,
            "EXECUTION_FAILED"
          );
        }
      });
    }
  }
  const clickToolCDP = new ClickTool();
  const fillToolSchema = {
    selector: string$1().optional().describe("CSS selector of the form element to fill (alternative to uid)"),
    uid: string$1().optional().describe(
      'Unique ID from accessibility tree snapshot (alternative to selector). Get this from chrome_accessibility_snapshot_cdp tool. Example: "1_42"'
    ),
    value: string$1().describe("The value to fill into the element"),
    clearFirst: boolean$1().default(true).describe("Whether to clear existing content first"),
    tabId: number$1().int().positive().optional().describe("Target tab ID (optional)")
  };
  class FillTool extends BaseBrowserToolExecutor {
    constructor() {
      super(...arguments);
      __publicField2(this, "name", TOOL_NAMES.BROWSER.FILL);
      __publicField2(this, "description", "Fill form elements using CSS selector or UID from accessibility snapshot (CDP version). RECOMMENDED: Use chrome_accessibility_snapshot_cdp to get UIDs for reliable element targeting. Supports automatic clearing, event triggering, and reliable input handling.");
      __publicField2(this, "annotations", {
        title: "Fill Form Element",
        category: ToolCategory.INPUT,
        readOnlyHint: false
      });
      __publicField2(this, "schema", fillToolSchema);
    }
    /**
     * 执行填充操作
     */
    execute(args) {
      return __async(this, null, function* () {
        console.warn(`开始执行 CDP 填充操作，原始参数:`, args);
        const validationResult = this.validateArgs(args);
        if (!validationResult.success) {
          return validationResult.error;
        }
        const { selector, uid, value, clearFirst, tabId } = validationResult.data;
        console.warn(`参数验证通过，处理后的参数:`, validationResult.data);
        if (!selector && !uid) {
          return error$J(
            'Must provide either selector or uid\n\nUsage examples:\n1. Use selector: { selector: "#email", value: "test@example.com" }\n2. Use uid: { uid: "1_42", value: "test@example.com" }',
            "INVALID_PARAMETERS"
          );
        }
        try {
          const targetTab = yield cdpDebuggerManager.getTargetTab(tabId);
          const targetTabId = targetTab.id;
          return yield cdpSessionExecutor.executeWithSession(targetTabId, (session, viewport) => __async(this, null, function* () {
            var _a3, _b2, _c2, _d2, _e, _f, _g;
            let finalSelector;
            if (uid) {
              const backendNodeId = getBackendNodeIdByUid(uid);
              if (!backendNodeId) {
                return error$J(
                  `Element not found for UID "${uid}". The UID may be stale. Please capture a new snapshot using chrome_accessibility_snapshot_cdp.`,
                  "ELEMENT_NOT_FOUND",
                  { uid }
                );
              }
              console.warn("[CDP 填充] 通过UID定位元素:", uid, "→ backendNodeId:", backendNodeId);
              yield cdpScrollHelper.scrollElementByBackendNodeIdToCenter(targetTabId, backendNodeId);
              finalSelector = `[data-snapshot-uid="${uid}"]`;
              console.warn("[CDP 填充] UID定位成功，使用唯一选择器:", finalSelector);
              const elementExistsResult = yield session.send("Runtime.evaluate", {
                expression: `!!document.querySelector('[data-snapshot-uid="${uid}"]')`,
                returnByValue: true
              });
              if (!((_a3 = elementExistsResult == null ? void 0 : elementExistsResult.result) == null ? void 0 : _a3.value)) {
                return error$J(
                  `Element with UID "${uid}" not found in current page state.`,
                  "ELEMENT_NOT_FOUND",
                  { uid }
                );
              }
            } else {
              finalSelector = selector;
              console.warn("[CDP 填充] Selector定位，使用选择器:", finalSelector);
            }
            console.error("[CDP 填充] ===== 最终使用的选择器 =====", finalSelector);
            const getElementInfoExpression = `
          (function() {
            const element = document.querySelector(${JSON.stringify(finalSelector)});
            if (!element) return { error: 'Element not found' };

            // 检查元素可见性
            const style = window.getComputedStyle(element);
            const isVisible = style.display !== 'none' &&
                             style.visibility !== 'hidden' &&
                             style.opacity !== '0';

            if (!isVisible) {
              return { error: 'Element is not visible' };
            }

            // 检查元素是否可填充
            const validTags = ['INPUT', 'TEXTAREA', 'SELECT'];
            const validInputTypes = [
              'text', 'email', 'password', 'number', 'search',
              'tel', 'url', 'date', 'datetime-local', 'month',
              'time', 'week', 'color'
            ];

            const isContentEditable = element.contentEditable === 'true' || element.contentEditable === '';

            if (!validTags.includes(element.tagName) && !isContentEditable) {
              return {
                error: 'Element is not fillable (must be INPUT, TEXTAREA, SELECT, or contenteditable)',
                tagName: element.tagName
              };
            }

            // 对于 input 元素，检查类型
            if (element.tagName === 'INPUT' &&
                !validInputTypes.includes(element.type) &&
                element.type !== null) {
              return {
                error: \`Input type "\${element.type}" is not fillable\`,
                type: element.type
              };
            }

            const rect = element.getBoundingClientRect();

            return {
              tagName: element.tagName,
              id: element.id,
              className: element.className,
              type: element.type || null,
              isContentEditable: isContentEditable,
              isVisible: true,
              currentValue: element.tagName === 'SELECT' ? element.value :
                           isContentEditable ? element.textContent : element.value,
              rect: {
                x: rect.x,
                y: rect.y,
                width: rect.width,
                height: rect.height,
                top: rect.top,
                right: rect.right,
                bottom: rect.bottom,
                left: rect.left,
              },
            };
          })()
        `;
            const elementResult = yield session.send("Runtime.evaluate", {
              expression: getElementInfoExpression,
              returnByValue: true
            });
            const elementInfo = (_b2 = elementResult == null ? void 0 : elementResult.result) == null ? void 0 : _b2.value;
            if (elementInfo == null ? void 0 : elementInfo.error) {
              const errorCode = elementInfo.error.includes("not visible") ? "ELEMENT_NOT_VISIBLE" : elementInfo.error.includes("not fillable") ? "ELEMENT_NOT_INTERACTABLE" : "ELEMENT_NOT_FOUND";
              return error$J(
                `Element error: ${elementInfo.error}. Selector: "${finalSelector}"`,
                errorCode,
                {
                  selector: finalSelector,
                  uid,
                  errorDetail: elementInfo.error
                }
              );
            }
            if (!elementInfo) {
              return error$J(`Element with selector "${finalSelector}" not found`, "ELEMENT_NOT_FOUND", {
                selector: finalSelector,
                uid
              });
            }
            console.warn("[CDP 填充] 元素信息:", elementInfo);
            const elementRect = elementInfo.rect;
            const clickX = elementRect.left + elementRect.width / 2;
            const clickY = elementRect.top + elementRect.height / 2;
            yield session.send("Input.dispatchMouseEvent", {
              type: "mousePressed",
              x: clickX,
              y: clickY,
              button: "left",
              clickCount: 1
            });
            yield new Promise((resolve2) => setTimeout(resolve2, 20));
            yield session.send("Input.dispatchMouseEvent", {
              type: "mouseReleased",
              x: clickX,
              y: clickY,
              button: "left",
              clickCount: 1
            });
            console.warn("[CDP 填充] 已通过 CDP 点击聚焦元素");
            yield new Promise((resolve2) => setTimeout(resolve2, 100));
            if (elementInfo.tagName === "SELECT") {
              const selectExpression = `
            (function() {
              const element = document.querySelector(${JSON.stringify(finalSelector)});
              if (!element) return { error: 'Element not found' };

              let optionFound = false;
              for (const option of element.options) {
                if (option.value === ${JSON.stringify(value)} || option.text === ${JSON.stringify(value)}) {
                  element.value = option.value;
                  optionFound = true;
                  break;
                }
              }

              if (!optionFound) {
                return { error: 'No matching option found' };
              }

              // 触发事件
              element.dispatchEvent(new Event('input', { bubbles: true }));
              element.dispatchEvent(new Event('change', { bubbles: true }));

              return { success: true, value: element.value };
            })()
          `;
              const selectResult = yield session.send("Runtime.evaluate", {
                expression: selectExpression,
                returnByValue: true
              });
              const selectValue = (_c2 = selectResult == null ? void 0 : selectResult.result) == null ? void 0 : _c2.value;
              if (selectValue == null ? void 0 : selectValue.error) {
                return error$J(
                  `Failed to select option: ${selectValue.error}. Value: "${value}"`,
                  "EXECUTION_FAILED",
                  { selector: finalSelector, uid, value, errorDetail: selectValue.error }
                );
              }
              console.warn("[CDP 填充] SELECT 元素已设置:", selectValue == null ? void 0 : selectValue.value);
            } else {
              console.warn("[CDP 填充] clearFirst 参数值:", clearFirst);
              console.warn("[CDP 填充] 当前元素值:", elementInfo.currentValue);
              if (clearFirst) {
                console.warn("[CDP 填充] 开始执行清空操作...");
                const selectAllExpression = `
              (function() {
                const element = document.querySelector(${JSON.stringify(finalSelector)});
                if (!element) return { error: 'Element not found' };

                const isInputOrTextarea = element.tagName === 'INPUT' || element.tagName === 'TEXTAREA';

                if (isInputOrTextarea) {
                  // 对于 input/textarea，设置选中范围为全部内容
                  element.focus();
                  element.setSelectionRange(0, element.value.length);
                  return {
                    method: 'setSelectionRange',
                    selectionStart: element.selectionStart,
                    selectionEnd: element.selectionEnd,
                    valueLength: element.value.length,
                  };
                } else {
                  // 对于 contenteditable，使用 selectAllChildren
                  element.focus();
                  const range = document.createRange();
                  range.selectNodeContents(element);
                  const selection = window.getSelection();
                  selection.removeAllRanges();
                  selection.addRange(range);
                  return {
                    method: 'selectNodeContents',
                    selectionText: selection.toString(),
                  };
                }
              })()
            `;
                const selectAllResult = yield session.send("Runtime.evaluate", {
                  expression: selectAllExpression,
                  returnByValue: true
                });
                const selectAllInfo = (_d2 = selectAllResult == null ? void 0 : selectAllResult.result) == null ? void 0 : _d2.value;
                console.warn("[CDP 填充] 通过 JS 全选内容:", selectAllInfo);
                yield new Promise((resolve2) => setTimeout(resolve2, 50));
                const checkSelectionExpression = `
              (function() {
                const element = document.querySelector(${JSON.stringify(finalSelector)});
                if (!element) return { error: 'Element not found' };

                const isContentEditable = element.contentEditable === 'true' || element.contentEditable === '';
                const isInputOrTextarea = element.tagName === 'INPUT' || element.tagName === 'TEXTAREA';

                let selectionInfo = {};

                if (isInputOrTextarea) {
                  // 对于 input/textarea，检查 selectionStart 和 selectionEnd
                  selectionInfo = {
                    selectionStart: element.selectionStart,
                    selectionEnd: element.selectionEnd,
                    selectedLength: element.selectionEnd - element.selectionStart,
                    elementValue: element.value,
                    valueLength: element.value ? element.value.length : 0,
                  };
                } else {
                  // 对于 contenteditable，使用 window.getSelection
                  const selection = window.getSelection();
                  const selectionText = selection ? selection.toString() : '';
                  selectionInfo = {
                    selectionLength: selectionText.length,
                    selectionText: selectionText,
                    elementValue: element.textContent,
                  };
                }

                return selectionInfo;
              })()
            `;
                const selectionResult = yield session.send("Runtime.evaluate", {
                  expression: checkSelectionExpression,
                  returnByValue: true
                });
                const selectionInfo = (_e = selectionResult == null ? void 0 : selectionResult.result) == null ? void 0 : _e.value;
                console.warn("[CDP 填充] 全选后的选中状态:", selectionInfo);
              } else {
                console.warn("[CDP 填充] clearFirst=false，跳过清空操作");
              }
              console.warn("[CDP 填充] 准备逐字符插入文本:", value);
              for (let i2 = 0; i2 < value.length; i2++) {
                const char = value[i2];
                yield session.send("Input.insertText", {
                  text: char
                });
                if (i2 < value.length - 1) {
                  const delay = 30 + Math.random() * 50;
                  yield new Promise((resolve2) => setTimeout(resolve2, delay));
                }
              }
              console.warn("[CDP 填充] 已通过 CDP Input.insertText 逐字符插入文本:", value);
              yield new Promise((resolve2) => setTimeout(resolve2, 50));
              const checkValueExpression = `
            (function() {
              const element = document.querySelector(${JSON.stringify(finalSelector)});
              if (!element) return { error: 'Element not found' };

              const isContentEditable = element.contentEditable === 'true' || element.contentEditable === '';
              const currentValue = isContentEditable ? element.textContent : element.value;

              return {
                currentValue: currentValue,
                valueLength: currentValue ? currentValue.length : 0,
              };
            })()
          `;
              const checkValueResult = yield session.send("Runtime.evaluate", {
                expression: checkValueExpression,
                returnByValue: true
              });
              const valueInfo = (_f = checkValueResult == null ? void 0 : checkValueResult.result) == null ? void 0 : _f.value;
              console.warn("[CDP 填充] 插入文本后的元素值:", valueInfo);
            }
            const verifyExpression = `
          (function() {
            const element = document.querySelector(${JSON.stringify(finalSelector)});
            if (!element) return { error: 'Element not found' };

            const isContentEditable = element.contentEditable === 'true' || element.contentEditable === '';
            const finalValue = element.tagName === 'SELECT' ? element.value :
                              isContentEditable ? element.textContent : element.value;

            return {
              success: true,
              finalValue: finalValue,
              valueLength: finalValue ? finalValue.length : 0,
            };
          })()
        `;
            const verifyResult = yield session.send("Runtime.evaluate", {
              expression: verifyExpression,
              returnByValue: true
            });
            const verification = (_g = verifyResult == null ? void 0 : verifyResult.result) == null ? void 0 : _g.value;
            console.warn("[CDP 填充] 填充验证:", verification);
            yield cdpHighlighter.highlightFill(targetTabId, finalSelector);
            return success$1(`Filled input with '${value}'`, {
              selector: finalSelector,
              uid,
              value,
              elementType: elementInfo.tagName
            });
          }));
        } catch (err) {
          console.error("CDP 填充操作错误:", err);
          return error$J(
            `执行填充时出错: ${err instanceof Error ? err.message : String(err)}`,
            "EXECUTION_FAILED",
            {
              selector: args.selector,
              stack: err instanceof Error ? err.stack : void 0
            }
          );
        }
      });
    }
  }
  const fillTool = new FillTool();
  const keyboardToolSchema = {
    keys: string$1().min(1).describe(
      'Keys to simulate (e.g., "Enter", "Ctrl+C", "A, B, C"). Supports special keys, modifiers, and sequences separated by commas.'
    ),
    selector: string$1().optional().describe(
      "CSS selector of the target element to focus before sending keys. If not provided, sends keys to the currently focused element."
    ),
    delay: number$1().int().nonnegative().default(TIMEOUTS.KEYBOARD_DELAY).describe(`Delay between key sequences in milliseconds. Default: ${TIMEOUTS.KEYBOARD_DELAY}ms`),
    tabId: number$1().int().positive().optional().describe("Target tab ID. If not provided, uses the currently active tab.")
  };
  const SPECIAL_KEY_MAP = {
    enter: {
      key: "Enter",
      code: "Enter",
      keyCode: 13,
      windowsVirtualKeyCode: 13,
      nativeVirtualKeyCode: 13,
      text: "\r",
      // Enter 键产生回车符
      location: 0,
      // 标准位置
      isKeypad: false
    },
    tab: { key: "Tab", code: "Tab", keyCode: 9, windowsVirtualKeyCode: 9, nativeVirtualKeyCode: 9 },
    esc: {
      key: "Escape",
      code: "Escape",
      keyCode: 27,
      windowsVirtualKeyCode: 27,
      nativeVirtualKeyCode: 27
    },
    escape: {
      key: "Escape",
      code: "Escape",
      keyCode: 27,
      windowsVirtualKeyCode: 27,
      nativeVirtualKeyCode: 27
    },
    space: {
      key: " ",
      code: "Space",
      keyCode: 32,
      windowsVirtualKeyCode: 32,
      nativeVirtualKeyCode: 32
    },
    backspace: {
      key: "Backspace",
      code: "Backspace",
      keyCode: 8,
      windowsVirtualKeyCode: 8,
      nativeVirtualKeyCode: 8
    },
    delete: {
      key: "Delete",
      code: "Delete",
      keyCode: 46,
      windowsVirtualKeyCode: 46,
      nativeVirtualKeyCode: 46
    },
    del: {
      key: "Delete",
      code: "Delete",
      keyCode: 46,
      windowsVirtualKeyCode: 46,
      nativeVirtualKeyCode: 46
    },
    up: {
      key: "ArrowUp",
      code: "ArrowUp",
      keyCode: 38,
      windowsVirtualKeyCode: 38,
      nativeVirtualKeyCode: 38
    },
    arrowup: {
      key: "ArrowUp",
      code: "ArrowUp",
      keyCode: 38,
      windowsVirtualKeyCode: 38,
      nativeVirtualKeyCode: 38
    },
    down: {
      key: "ArrowDown",
      code: "ArrowDown",
      keyCode: 40,
      windowsVirtualKeyCode: 40,
      nativeVirtualKeyCode: 40
    },
    arrowdown: {
      key: "ArrowDown",
      code: "ArrowDown",
      keyCode: 40,
      windowsVirtualKeyCode: 40,
      nativeVirtualKeyCode: 40
    },
    left: {
      key: "ArrowLeft",
      code: "ArrowLeft",
      keyCode: 37,
      windowsVirtualKeyCode: 37,
      nativeVirtualKeyCode: 37
    },
    arrowleft: {
      key: "ArrowLeft",
      code: "ArrowLeft",
      keyCode: 37,
      windowsVirtualKeyCode: 37,
      nativeVirtualKeyCode: 37
    },
    right: {
      key: "ArrowRight",
      code: "ArrowRight",
      keyCode: 39,
      windowsVirtualKeyCode: 39,
      nativeVirtualKeyCode: 39
    },
    arrowright: {
      key: "ArrowRight",
      code: "ArrowRight",
      keyCode: 39,
      windowsVirtualKeyCode: 39,
      nativeVirtualKeyCode: 39
    },
    home: {
      key: "Home",
      code: "Home",
      keyCode: 36,
      windowsVirtualKeyCode: 36,
      nativeVirtualKeyCode: 36
    },
    end: {
      key: "End",
      code: "End",
      keyCode: 35,
      windowsVirtualKeyCode: 35,
      nativeVirtualKeyCode: 35
    },
    pageup: {
      key: "PageUp",
      code: "PageUp",
      keyCode: 33,
      windowsVirtualKeyCode: 33,
      nativeVirtualKeyCode: 33
    },
    pagedown: {
      key: "PageDown",
      code: "PageDown",
      keyCode: 34,
      windowsVirtualKeyCode: 34,
      nativeVirtualKeyCode: 34
    },
    insert: {
      key: "Insert",
      code: "Insert",
      keyCode: 45,
      windowsVirtualKeyCode: 45,
      nativeVirtualKeyCode: 45
    },
    // Function keys
    f1: {
      key: "F1",
      code: "F1",
      keyCode: 112,
      windowsVirtualKeyCode: 112,
      nativeVirtualKeyCode: 112
    },
    f2: {
      key: "F2",
      code: "F2",
      keyCode: 113,
      windowsVirtualKeyCode: 113,
      nativeVirtualKeyCode: 113
    },
    f3: {
      key: "F3",
      code: "F3",
      keyCode: 114,
      windowsVirtualKeyCode: 114,
      nativeVirtualKeyCode: 114
    },
    f4: {
      key: "F4",
      code: "F4",
      keyCode: 115,
      windowsVirtualKeyCode: 115,
      nativeVirtualKeyCode: 115
    },
    f5: {
      key: "F5",
      code: "F5",
      keyCode: 116,
      windowsVirtualKeyCode: 116,
      nativeVirtualKeyCode: 116
    },
    f6: {
      key: "F6",
      code: "F6",
      keyCode: 117,
      windowsVirtualKeyCode: 117,
      nativeVirtualKeyCode: 117
    },
    f7: {
      key: "F7",
      code: "F7",
      keyCode: 118,
      windowsVirtualKeyCode: 118,
      nativeVirtualKeyCode: 118
    },
    f8: {
      key: "F8",
      code: "F8",
      keyCode: 119,
      windowsVirtualKeyCode: 119,
      nativeVirtualKeyCode: 119
    },
    f9: {
      key: "F9",
      code: "F9",
      keyCode: 120,
      windowsVirtualKeyCode: 120,
      nativeVirtualKeyCode: 120
    },
    f10: {
      key: "F10",
      code: "F10",
      keyCode: 121,
      windowsVirtualKeyCode: 121,
      nativeVirtualKeyCode: 121
    },
    f11: {
      key: "F11",
      code: "F11",
      keyCode: 122,
      windowsVirtualKeyCode: 122,
      nativeVirtualKeyCode: 122
    },
    f12: {
      key: "F12",
      code: "F12",
      keyCode: 123,
      windowsVirtualKeyCode: 123,
      nativeVirtualKeyCode: 123
    }
  };
  const MODIFIER_KEYS = {
    ctrl: "ctrlKey",
    control: "ctrlKey",
    alt: "altKey",
    shift: "shiftKey",
    meta: "metaKey",
    command: "metaKey",
    cmd: "metaKey"
  };
  const CDP_MODIFIERS = {
    Alt: 1,
    Ctrl: 2,
    Meta: 4,
    Shift: 8
  };
  class KeyboardTool extends BaseBrowserToolExecutor {
    constructor() {
      super(...arguments);
      __publicField2(this, "name", TOOL_NAMES.BROWSER.KEYBOARD);
      __publicField2(this, "description", "Simulate keyboard input using CDP. Supports special keys (Enter, Tab, Arrow keys, etc.), key combinations (Ctrl+C, Shift+A), and sequences. Can target specific elements or the currently focused element.");
      __publicField2(this, "annotations", {
        title: "Keyboard Input",
        category: ToolCategory.INPUT,
        readOnlyHint: false
      });
      __publicField2(this, "schema", keyboardToolSchema);
    }
    /**
     * 解析单个按键组合字符串
     * @param keyString - 按键字符串（例如 "Ctrl+A"、"Enter"、"a"）
     * @returns 解析后的按键信息
     */
    parseSingleKeyCombination(keyString) {
      var _a3, _b2;
      const parts = keyString.split("+").map((part) => part.trim().toLowerCase());
      const modifiers = {
        ctrlKey: false,
        altKey: false,
        shiftKey: false,
        metaKey: false
      };
      let mainKeyPart = null;
      for (const part of parts) {
        if (MODIFIER_KEYS[part]) {
          modifiers[MODIFIER_KEYS[part]] = true;
        } else if (mainKeyPart === null) {
          mainKeyPart = part;
        } else {
          console.error(`Invalid key combination: ${keyString}. Multiple main keys found.`);
          return null;
        }
      }
      if (!mainKeyPart) {
        if (parts.length === 1 && MODIFIER_KEYS[parts[0]]) {
          const modKey = parts[0];
          const emptyModifiers = {
            ctrlKey: false,
            altKey: false,
            shiftKey: false,
            metaKey: false
          };
          if (modKey === "ctrl" || modKey === "control") {
            return {
              key: "Control",
              code: "ControlLeft",
              keyCode: 17,
              windowsVirtualKeyCode: 17,
              nativeVirtualKeyCode: 17,
              location: 1,
              // 左侧
              isKeypad: false,
              modifiers: emptyModifiers,
              cdpModifiers: 0
            };
          }
          if (modKey === "alt") {
            return {
              key: "Alt",
              code: "AltLeft",
              keyCode: 18,
              windowsVirtualKeyCode: 18,
              nativeVirtualKeyCode: 18,
              location: 1,
              // 左侧
              isKeypad: false,
              modifiers: emptyModifiers,
              cdpModifiers: 0
            };
          }
          if (modKey === "shift") {
            return {
              key: "Shift",
              code: "ShiftLeft",
              keyCode: 16,
              windowsVirtualKeyCode: 16,
              nativeVirtualKeyCode: 16,
              location: 1,
              // 左侧
              isKeypad: false,
              modifiers: emptyModifiers,
              cdpModifiers: 0
            };
          }
          if (modKey === "meta" || modKey === "command" || modKey === "cmd") {
            return {
              key: "Meta",
              code: "MetaLeft",
              keyCode: 91,
              windowsVirtualKeyCode: 91,
              nativeVirtualKeyCode: 91,
              location: 1,
              // 左侧
              isKeypad: false,
              modifiers: emptyModifiers,
              cdpModifiers: 0
            };
          }
        }
        console.error(`Invalid key combination: ${keyString}. No main key specified.`);
        return null;
      }
      let cdpModifiers = 0;
      if (modifiers.altKey) cdpModifiers |= CDP_MODIFIERS.Alt;
      if (modifiers.ctrlKey) cdpModifiers |= CDP_MODIFIERS.Ctrl;
      if (modifiers.metaKey) cdpModifiers |= CDP_MODIFIERS.Meta;
      if (modifiers.shiftKey) cdpModifiers |= CDP_MODIFIERS.Shift;
      const specialKey = SPECIAL_KEY_MAP[mainKeyPart];
      if (specialKey) {
        const hasNonShiftModifier = modifiers.ctrlKey || modifiers.altKey || modifiers.metaKey;
        const text = hasNonShiftModifier ? void 0 : specialKey.text;
        return __spreadProps(__spreadValues({}, specialKey), {
          text,
          // 可能被清空（如果有修饰符）
          modifiers,
          cdpModifiers,
          location: (_a3 = specialKey.location) != null ? _a3 : 0,
          // 确保有默认值
          isKeypad: (_b2 = specialKey.isKeypad) != null ? _b2 : false
          // 确保有默认值
        });
      }
      if (mainKeyPart.length === 1) {
        const char = mainKeyPart;
        let displayChar = char;
        if (modifiers.shiftKey && char.match(/^[a-z]$/)) {
          displayChar = char.toUpperCase();
        }
        const keyCode = char.toUpperCase().charCodeAt(0);
        const hasNonShiftModifier = modifiers.ctrlKey || modifiers.altKey || modifiers.metaKey;
        const text = hasNonShiftModifier ? void 0 : displayChar;
        return {
          key: displayChar,
          code: char.match(/^[a-z]$/i) ? `Key${char.toUpperCase()}` : char,
          keyCode,
          windowsVirtualKeyCode: keyCode,
          nativeVirtualKeyCode: keyCode,
          text,
          location: 0,
          // 普通字符键都在标准位置
          isKeypad: false,
          // 普通字符键不在数字小键盘
          modifiers,
          cdpModifiers
        };
      }
      console.error(`Unknown key: ${mainKeyPart}`);
      return null;
    }
    /**
     * 通过 CDP 发送按键事件
     */
    dispatchKeyEvent(session, type2, keyInfo) {
      return __async(this, null, function* () {
        var _a3, _b2;
        const params = {
          type: type2,
          modifiers: keyInfo.cdpModifiers,
          key: keyInfo.key,
          code: keyInfo.code
        };
        if (type2 === "keyDown" || type2 === "keyUp" || type2 === "rawKeyDown") {
          if (keyInfo.windowsVirtualKeyCode !== void 0) {
            params.windowsVirtualKeyCode = keyInfo.windowsVirtualKeyCode;
          }
          if (keyInfo.nativeVirtualKeyCode !== void 0) {
            params.nativeVirtualKeyCode = keyInfo.nativeVirtualKeyCode;
          }
        }
        if (type2 === "keyDown" && keyInfo.text) {
          params.text = keyInfo.text;
          params.unmodifiedText = keyInfo.text;
        } else if (type2 === "char" && keyInfo.text) {
          params.text = keyInfo.text;
        }
        params.autoRepeat = false;
        params.location = (_a3 = keyInfo.location) != null ? _a3 : 0;
        params.isKeypad = (_b2 = keyInfo.isKeypad) != null ? _b2 : false;
        yield session.send("Input.dispatchKeyEvent", params);
      });
    }
    /**
     * 模拟完整的按键操作（考虑修饰键的正确顺序）
     */
    simulateSingleKey(session, keyInfo) {
      return __async(this, null, function* () {
        const hasModifiers = keyInfo.modifiers.ctrlKey || keyInfo.modifiers.altKey || keyInfo.modifiers.shiftKey || keyInfo.modifiers.metaKey;
        const modifierKeys = [];
        if (hasModifiers) {
          if (keyInfo.modifiers.metaKey) {
            modifierKeys.push({
              key: "Meta",
              code: "MetaLeft",
              keyCode: 91,
              windowsVirtualKeyCode: 91
            });
          }
          if (keyInfo.modifiers.ctrlKey) {
            modifierKeys.push({
              key: "Control",
              code: "ControlLeft",
              keyCode: 17,
              windowsVirtualKeyCode: 17
            });
          }
          if (keyInfo.modifiers.altKey) {
            modifierKeys.push({ key: "Alt", code: "AltLeft", keyCode: 18, windowsVirtualKeyCode: 18 });
          }
          if (keyInfo.modifiers.shiftKey) {
            modifierKeys.push({
              key: "Shift",
              code: "ShiftLeft",
              keyCode: 16,
              windowsVirtualKeyCode: 16
            });
          }
          for (const modKey of modifierKeys) {
            yield session.send("Input.dispatchKeyEvent", {
              type: "rawKeyDown",
              key: modKey.key,
              code: modKey.code,
              windowsVirtualKeyCode: modKey.windowsVirtualKeyCode,
              nativeVirtualKeyCode: modKey.windowsVirtualKeyCode,
              modifiers: 0,
              autoRepeat: false,
              location: 1,
              // 左侧修饰键
              isKeypad: false
            });
            console.log(`[CDP 键盘] 按下修饰键: ${modKey.key}`);
            yield new Promise((resolve2) => setTimeout(resolve2, 10));
          }
        }
        const keyDownType = keyInfo.text ? "keyDown" : "rawKeyDown";
        yield this.dispatchKeyEvent(session, keyDownType, keyInfo);
        console.log(
          `[CDP 键盘] ${keyDownType}: ${keyInfo.key}${keyInfo.text ? ` (text: ${JSON.stringify(keyInfo.text)})` : ""}${hasModifiers ? " (with modifiers)" : ""}`
        );
        yield new Promise((resolve2) => setTimeout(resolve2, 10));
        yield this.dispatchKeyEvent(session, "keyUp", keyInfo);
        console.log(`[CDP 键盘] keyUp: ${keyInfo.key}`);
        if (hasModifiers) {
          yield new Promise((resolve2) => setTimeout(resolve2, 10));
          for (const modKey of modifierKeys.reverse()) {
            yield session.send("Input.dispatchKeyEvent", {
              type: "keyUp",
              key: modKey.key,
              code: modKey.code,
              windowsVirtualKeyCode: modKey.windowsVirtualKeyCode,
              nativeVirtualKeyCode: modKey.windowsVirtualKeyCode,
              modifiers: 0,
              autoRepeat: false,
              location: 1,
              isKeypad: false
            });
            console.log(`[CDP 键盘] 释放修饰键: ${modKey.key}`);
            yield new Promise((resolve2) => setTimeout(resolve2, 10));
          }
        }
      });
    }
    /**
     * 执行键盘操作
     */
    execute(args) {
      return __async(this, null, function* () {
        console.log(`开始执行 CDP 键盘操作，原始参数:`, args);
        const validationResult = this.validateArgs(args);
        if (!validationResult.success) {
          return validationResult.error;
        }
        const { keys, selector, delay, tabId } = validationResult.data;
        console.log(`参数验证通过，处理后的参数:`, validationResult.data);
        let targetTab;
        try {
          targetTab = yield cdpDebuggerManager.getTargetTab(tabId);
          const targetTabId = targetTab.id;
          const result2 = yield cdpSessionExecutor.executeWithSession(
            targetTabId,
            (session, viewport) => __async(this, null, function* () {
              let targetElement = null;
              if (selector) {
                targetElement = yield cdpElementHelper.focusElement(targetTabId, selector);
                if (!targetElement.success) {
                  return error$J(
                    `Element error: ${targetElement.error}. Selector: "${selector}"`,
                    "ELEMENT_NOT_FOUND",
                    { selector, error: targetElement.error }
                  );
                }
                yield new Promise((resolve2) => setTimeout(resolve2, 50));
              }
              const keyCombinations = keys.split(",").map((k) => k.trim()).filter((k) => k.length > 0);
              const operationResults = [];
              for (let i2 = 0; i2 < keyCombinations.length; i2++) {
                const comboString = keyCombinations[i2];
                const parsedKeyInfo = this.parseSingleKeyCombination(comboString);
                if (!parsedKeyInfo) {
                  operationResults.push({
                    keyCombination: comboString,
                    success: false,
                    error: `Invalid key combination: ${comboString}`
                  });
                  console.warn(`跳过无效的按键组合: ${comboString}`);
                  continue;
                }
                try {
                  yield this.simulateSingleKey(session, parsedKeyInfo);
                  operationResults.push({
                    keyCombination: comboString,
                    success: true
                  });
                } catch (error2) {
                  const errorMsg = error2 instanceof Error ? error2.message : String(error2);
                  operationResults.push({
                    keyCombination: comboString,
                    success: false,
                    error: `Failed to simulate key: ${errorMsg}`
                  });
                  console.error(`模拟按键失败 "${comboString}":`, error2);
                }
                if (delay > 0 && i2 < keyCombinations.length - 1) {
                  yield new Promise((resolve2) => setTimeout(resolve2, delay));
                }
              }
              const overallSuccess = operationResults.every((r) => r.success);
              if (!overallSuccess) {
                return error$J(`Some keyboard events failed for: ${keys}`, "EXECUTION_ERROR", {
                  totalKeys: keyCombinations.length,
                  successCount: operationResults.filter((r) => r.success).length,
                  failureCount: operationResults.filter((r) => !r.success).length,
                  results: operationResults
                });
              }
              return success$1(`Pressed ${keys}`, {
                keys,
                totalKeys: keyCombinations.length,
                targetElement,
                results: operationResults
              });
            })
          );
          return result2;
        } catch (err) {
          console.error("CDP 键盘操作错误:", err);
          return error$J(
            `执行键盘操作时出错: ${err instanceof Error ? err.message : String(err)}`,
            err instanceof Error && err.message.includes("No active tab") ? "NO_ACTIVE_TAB" : "EXECUTION_ERROR",
            {
              stack: err instanceof Error ? err.stack : void 0
            }
          );
        }
      });
    }
  }
  const keyboardTool = new KeyboardTool();
  const scrollToolSchema = {
    direction: _enum$1(["up", "down", "left", "right"]).optional().describe(
      'Scroll direction. Required if "target" is not provided. Options: "up", "down", "left", "right".'
    ),
    distance: number$1().positive().optional().describe("Scroll distance in pixels. Default: 300 if not provided."),
    target: _enum$1(["top", "bottom", "left-edge", "right-edge"]).optional().describe(
      'Scroll to a boundary position. Options: "top" (scroll to page top), "bottom" (scroll to page bottom), "left-edge" (scroll to left edge), "right-edge" (scroll to right edge). When specified, "direction" and "distance" are ignored.'
    ),
    coordinates: object({
      x: number$1().describe("X coordinate relative to viewport"),
      y: number$1().describe("Y coordinate relative to viewport")
    }).optional().describe(
      "Coordinates where the scroll event is triggered. If not provided, uses element center or viewport center."
    ),
    selector: string$1().optional().describe("CSS selector of the element to scroll. If not provided, scrolls the page."),
    smooth: boolean$1().optional().describe(
      "Enable smooth scrolling (Note: CDP does not support smooth scrolling, this parameter is for interface compatibility only)"
    ),
    timeout: number$1().positive().default(TIMEOUTS.DEFAULT_WAIT * 3).describe(`Maximum time to wait in milliseconds. Default: ${TIMEOUTS.DEFAULT_WAIT * 3}ms`),
    tabId: number$1().int().positive().optional().describe("Target tab ID. If not provided, uses the currently active tab.")
  };
  class ScrollTool extends BaseBrowserToolExecutor {
    constructor() {
      super(...arguments);
      __publicField2(this, "name", TOOL_NAMES.BROWSER.SCROLL);
      __publicField2(this, "description", "Scroll the page or a specific element using CDP mouseWheel events. Supports two modes: 1) Directional scrolling (up/down/left/right) with custom distance, 2) Boundary scrolling (top/bottom/left-edge/right-edge). Can target specific elements by selector or coordinates.");
      __publicField2(this, "annotations", {
        title: "Scroll Page",
        category: ToolCategory.NAVIGATION,
        readOnlyHint: false
      });
      __publicField2(this, "schema", scrollToolSchema);
    }
    /**
     * 执行滚动操作
     * 通过 CDP 协议发送鼠标滚轮事件来实现页面滚动
     */
    execute(args) {
      return __async(this, null, function* () {
        console.log(`开始执行滚动操作，原始参数:`, args);
        const validationResult = this.validateArgs(args);
        if (!validationResult.success) {
          return validationResult.error;
        }
        const { direction, distance, target, coordinates, selector, timeout, tabId } = validationResult.data;
        if (target) {
          if (direction !== void 0 || distance !== void 0) {
            return error$J(
              'Parameter conflict: Cannot use "direction" or "distance" when "target" is specified. Please choose one of the following modes:\n1. Directional scrolling: Use "direction" + "distance"\n2. Target position scrolling: Use "target"',
              "INVALID_PARAMETERS",
              {
                providedParams: { target, direction, distance },
                suggestion: 'Remove either "target" or "direction"+"distance"'
              }
            );
          }
        } else {
          if (!direction) {
            return error$J(
              'Missing required parameter: Must provide either "direction" or "target".\n• Directional scrolling mode: Provide "direction" (required) and "distance" (optional, default 300)\n• Target position mode: Provide "target" (top/bottom/left-edge/right-edge)',
              "MISSING_REQUIRED_PARAMETER",
              {
                suggestion: 'Provide either "direction" or "target"'
              }
            );
          }
        }
        console.log(`参数验证通过，处理后的参数:`, validationResult.data);
        let targetTab;
        try {
          targetTab = yield cdpDebuggerManager.getTargetTab(tabId);
          const targetTabId = targetTab.id;
          const result2 = yield cdpSessionExecutor.executeWithSession(
            targetTabId,
            (session, viewport) => __async(this, null, function* () {
              var _a3, _b2;
              let mouseX = (_a3 = coordinates == null ? void 0 : coordinates.x) != null ? _a3 : 0;
              let mouseY = (_b2 = coordinates == null ? void 0 : coordinates.y) != null ? _b2 : 0;
              if (selector || !coordinates) {
                try {
                  if (selector) {
                    const elementRect = yield cdpElementHelper.getElementRect(targetTabId, selector);
                    if (elementRect) {
                      mouseX = elementRect.left + elementRect.width / 2;
                      mouseY = elementRect.top + elementRect.height / 2;
                    }
                  } else {
                    const viewportInfo = yield cdpElementHelper.getViewportInfo(targetTabId);
                    mouseX = viewportInfo.width / 2;
                    mouseY = viewportInfo.height / 2;
                  }
                } catch (error2) {
                  console.warn("通过 CDP 获取元素信息失败，使用默认坐标:", error2);
                  if (!coordinates) {
                    mouseX = 400;
                    mouseY = 400;
                  }
                }
              }
              const initialScroll = yield cdpScrollHelper.getCurrentScrollPosition(targetTabId);
              console.log("[CDP 滚动] 初始滚动位置:", initialScroll);
              let scrollMode;
              let finalPosition;
              if (target) {
                scrollMode = "target";
                const scrollInfo = yield cdpScrollHelper.getScrollInfo(targetTabId);
                const maxScrollX = Math.max(0, scrollInfo.scrollWidth - scrollInfo.clientWidth);
                const maxScrollY = Math.max(0, scrollInfo.scrollHeight - scrollInfo.clientHeight);
                console.log("[CDP 滚动] 滚动边界信息:", {
                  maxScrollX,
                  maxScrollY,
                  scrollWidth: scrollInfo.scrollWidth,
                  scrollHeight: scrollInfo.scrollHeight,
                  clientWidth: scrollInfo.clientWidth,
                  clientHeight: scrollInfo.clientHeight
                });
                let targetX = initialScroll.x;
                let targetY = initialScroll.y;
                switch (target) {
                  case "top":
                    targetY = 0;
                    break;
                  case "bottom":
                    targetY = maxScrollY;
                    break;
                  case "left-edge":
                    targetX = 0;
                    break;
                  case "right-edge":
                    targetX = maxScrollX;
                    break;
                }
                console.log("[CDP 滚动] 目标位置滚动:", {
                  target,
                  currentPosition: initialScroll,
                  targetPosition: { x: targetX, y: targetY }
                });
                yield cdpHighlighter.highlightScroll(targetTabId, mouseX, mouseY);
                yield cdpScrollHelper.scrollToPosition(targetTabId, targetX, targetY, mouseX, mouseY);
                finalPosition = { x: targetX, y: targetY };
              } else {
                scrollMode = "direction";
                const actualDistance = distance != null ? distance : 300;
                let deltaX = 0;
                let deltaY = 0;
                switch (direction) {
                  case "up":
                    deltaY = -actualDistance;
                    break;
                  case "down":
                    deltaY = actualDistance;
                    break;
                  case "left":
                    deltaX = -actualDistance;
                    break;
                  case "right":
                    deltaX = actualDistance;
                    break;
                }
                console.log("[CDP 滚动] 触发鼠标滚轮事件:", {
                  mouseX,
                  mouseY,
                  deltaX,
                  deltaY,
                  direction,
                  distance: actualDistance
                });
                yield cdpHighlighter.highlightScroll(targetTabId, mouseX, mouseY);
                yield cdpScrollHelper.scrollByDelta(targetTabId, deltaX, deltaY, mouseX, mouseY);
                finalPosition = {
                  x: initialScroll.x + deltaX,
                  y: initialScroll.y + deltaY
                };
              }
              const scrollResult = yield cdpScrollHelper.getScrollInfo(targetTabId);
              const actualFinalPosition = {
                x: scrollResult.scrollX || 0,
                y: scrollResult.scrollY || 0
              };
              console.log("[CDP 滚动] 最终滚动结果:", {
                mode: scrollMode,
                initialPosition: initialScroll,
                expectedPosition: finalPosition,
                actualPosition: actualFinalPosition
              });
              if (scrollMode === "target") {
                return success$1(`Scrolled to ${target}`, {
                  mode: "target",
                  target,
                  scrollMethod: selector ? "element" : coordinates ? "coordinates" : "viewport",
                  previousPosition: initialScroll,
                  currentPosition: actualFinalPosition,
                  scrollDistance: {
                    x: Math.abs(actualFinalPosition.x - initialScroll.x),
                    y: Math.abs(actualFinalPosition.y - initialScroll.y)
                  },
                  scrollInfo: {
                    scrollWidth: scrollResult.scrollWidth || 0,
                    scrollHeight: scrollResult.scrollHeight || 0,
                    clientWidth: scrollResult.clientWidth || 0,
                    clientHeight: scrollResult.clientHeight || 0,
                    maxScrollX: Math.max(
                      0,
                      (scrollResult.scrollWidth || 0) - (scrollResult.clientWidth || 0)
                    ),
                    maxScrollY: Math.max(
                      0,
                      (scrollResult.scrollHeight || 0) - (scrollResult.clientHeight || 0)
                    )
                  }
                });
              } else {
                const actualDistance = distance != null ? distance : 300;
                return success$1(`Scrolled ${direction} ${actualDistance}px`, {
                  mode: "direction",
                  direction,
                  distance: actualDistance,
                  scrollMethod: selector ? "element" : coordinates ? "coordinates" : "viewport",
                  previousPosition: initialScroll,
                  currentPosition: actualFinalPosition,
                  scrollDistance: {
                    x: Math.abs(actualFinalPosition.x - initialScroll.x),
                    y: Math.abs(actualFinalPosition.y - initialScroll.y)
                  },
                  scrollInfo: {
                    scrollWidth: scrollResult.scrollWidth || 0,
                    scrollHeight: scrollResult.scrollHeight || 0,
                    clientWidth: scrollResult.clientWidth || 0,
                    clientHeight: scrollResult.clientHeight || 0
                  }
                });
              }
            })
          );
          return result2;
        } catch (err) {
          console.error("滚动操作错误:", err);
          return error$J(
            `Error during scroll execution: ${err instanceof Error ? err.message : String(err)}`,
            err instanceof Error && err.message.includes("No active tab") ? "NO_ACTIVE_TAB" : "EXECUTION_ERROR",
            {
              stack: err instanceof Error ? err.stack : void 0
            }
          );
        }
      });
    }
  }
  const scrollTool = new ScrollTool();
  const scrollIntoViewToolSchema = {
    selector: string$1().min(1).optional().describe(
      'CSS selector of the element to scroll into view (alternative to uid). Example: "#my-element", ".item-class"'
    ),
    uid: string$1().optional().describe(
      'Unique ID from accessibility tree snapshot (alternative to selector). Get this from chrome_accessibility_snapshot_cdp tool. Example: "1_42"'
    ),
    behavior: _enum$1(["auto", "smooth"]).default("auto").describe(
      'Scroll behavior. Options: "auto", "smooth". Note: CDP does not support smooth scrolling. Default: "auto"'
    ),
    block: _enum$1(["start", "center", "end", "nearest"]).default("center").describe(
      'Vertical alignment. Options: "start", "center", "end", "nearest". Default: "center"'
    ),
    inline: _enum$1(["start", "center", "end", "nearest"]).default("center").describe(
      'Horizontal alignment. Options: "start", "center", "end", "nearest". Default: "center"'
    ),
    timeout: number$1().positive().default(TIMEOUTS.DEFAULT_WAIT * 3).describe(`Maximum time to wait in milliseconds. Default: ${TIMEOUTS.DEFAULT_WAIT * 3}ms`),
    tabId: number$1().int().positive().optional().describe("Target tab ID. If not provided, uses the currently active tab.")
  };
  class ScrollIntoViewTool extends BaseBrowserToolExecutor {
    constructor() {
      super(...arguments);
      __publicField2(this, "name", TOOL_NAMES.BROWSER.SCROLL_INTO_VIEW);
      __publicField2(this, "description", "Scroll an element into view using CSS selector or UID from accessibility snapshot. RECOMMENDED: Use chrome_accessibility_snapshot_cdp to get UIDs for reliable targeting. Supports customizable alignment (block and inline positioning) to control where the element appears in the viewport.");
      __publicField2(this, "annotations", {
        title: "Scroll Element Into View",
        category: ToolCategory.NAVIGATION,
        readOnlyHint: false
      });
      __publicField2(this, "schema", scrollIntoViewToolSchema);
    }
    /**
     * 执行滚动到视图操作
     */
    execute(args) {
      return __async(this, null, function* () {
        console.log(`开始执行 CDP 滚动到视图操作，原始参数:`, args);
        const validationResult = this.validateArgs(args);
        if (!validationResult.success) {
          return validationResult.error;
        }
        const { selector, uid, behavior, block, inline, timeout, tabId } = validationResult.data;
        console.log(`参数验证通过，处理后的参数:`, validationResult.data);
        if (!selector && !uid) {
          return error$J("Must provide either selector or uid", "INVALID_PARAMETERS");
        }
        try {
          const targetTab = yield cdpDebuggerManager.getTargetTab(tabId);
          const targetTabId = targetTab.id;
          return yield cdpSessionExecutor.executeWithSession(targetTabId, (session, viewport) => __async(this, null, function* () {
            if (uid) {
              const backendNodeId = getBackendNodeIdByUid(uid);
              if (!backendNodeId) {
                return error$J(
                  `Element not found for UID "${uid}". The UID may be stale. Please capture a new snapshot using chrome_accessibility_snapshot_cdp.`,
                  "ELEMENT_NOT_FOUND",
                  { uid }
                );
              }
              console.log("[CDP 滚动到视图] 通过UID滚动元素:", uid, "→ backendNodeId:", backendNodeId);
              const needsScroll2 = yield cdpScrollHelper.scrollElementByBackendNodeIdToPosition(
                targetTabId,
                backendNodeId,
                block,
                inline
              );
              return success$1(`Scrolled element into view`, {
                uid,
                block,
                inline,
                needsScroll: needsScroll2,
                method: "backendNodeId"
              });
            }
            const elementInfo = yield cdpElementHelper.findElement(targetTabId, selector);
            if (elementInfo.error) {
              return error$J(
                `Element error: ${elementInfo.error}. Selector: "${selector}"`,
                elementInfo.error.includes("not visible") ? "ELEMENT_NOT_VISIBLE" : "ELEMENT_NOT_FOUND",
                { selector, error: elementInfo.error }
              );
            }
            console.log("[CDP 滚动到视图] 元素信息:", elementInfo);
            const needsScroll = yield cdpScrollHelper.scrollElementIntoView(
              targetTabId,
              selector,
              block,
              inline
            );
            yield cdpHighlighter.highlightElement(targetTabId, selector);
            return success$1(`Scrolled element into view`, {
              selector,
              block,
              inline,
              needsScroll
            });
          }));
        } catch (err) {
          console.error("CDP 滚动到视图操作错误:", err);
          return error$J(
            `执行滚动到视图时出错: ${err instanceof Error ? err.message : String(err)}`,
            err instanceof Error && err.message.includes("No active tab") ? "NO_ACTIVE_TAB" : "EXECUTION_ERROR",
            {
              stack: err instanceof Error ? err.stack : void 0
            }
          );
        }
      });
    }
  }
  const scrollIntoViewTool = new ScrollIntoViewTool();
  const screenshotToolSchema = {
    // name: zod.string().describe('Screenshot filename'),
    selector: string$1().optional().describe("CSS selector to capture specific element"),
    fullPage: boolean$1().default(false).describe("Whether to capture full page"),
    // format: zod.enum(['png', 'jpeg', 'webp']).default('png').describe('Image format'),
    // quality: zod.number().min(0).max(100).default(80).describe('Image quality (0-100)'),
    tabId: number$1().int().min(1).optional().describe("Target tab ID (optional)")
  };
  class ScreenshotTool extends BaseBrowserToolExecutor {
    constructor() {
      super(...arguments);
      __publicField2(this, "name", TOOL_NAMES.BROWSER.SCREENSHOT);
      __publicField2(this, "description", "Capture screenshots using CDP. Supports full page, element capture, and background execution without activating the tab.");
      __publicField2(this, "annotations", {
        title: "Capture Screenshot",
        category: ToolCategory.DEBUGGING,
        readOnlyHint: true
      });
      __publicField2(this, "schema", screenshotToolSchema);
    }
    /**
     * 执行截图操作
     */
    execute(args) {
      return __async(this, null, function* () {
        var _a3, _b2, _c2, _d2;
        console.log("[CDP 截图] 开始执行，参数:", args);
        const validationResult = this.validateArgs(args);
        if (!validationResult.success) {
          return validationResult.error;
        }
        const { name: name2, selector, fullPage, format: format2 = "webp", quality, tabId } = validationResult.data;
        console.log("[CDP 截图] 尝试获取 tab:", tabId);
        if (tabId) {
          const allTabs = yield chrome.tabs.query({});
          const tabExists = allTabs.some((tab) => tab.id === tabId);
          console.log("[CDP 截图] Tab 存在性检查:", tabId, "存在:", tabExists);
          console.log(
            "[CDP 截图] 当前所有 tab IDs:",
            allTabs.map((t) => t.id)
          );
        }
        const targetTab = yield cdpDebuggerManager.getTargetTab(tabId, false);
        const targetTabId = targetTab.id;
        console.log("[CDP 截图] 成功获取 tab:", targetTabId, targetTab.url);
        if (((_a3 = targetTab.url) == null ? void 0 : _a3.startsWith("chrome://")) || ((_b2 = targetTab.url) == null ? void 0 : _b2.startsWith("edge://")) || ((_c2 = targetTab.url) == null ? void 0 : _c2.startsWith("https://chrome.google.com/webstore")) || ((_d2 = targetTab.url) == null ? void 0 : _d2.startsWith("https://microsoftedge.microsoft.com/"))) {
          return error$J(
            "Cannot capture special browser pages or web store pages due to security restrictions.",
            "EXECUTION_FAILED",
            {
              tab: targetTab,
              input: args
            }
          );
        }
        return yield cdpSessionExecutor.executeWithSession(targetTabId, (session, viewport) => __async(this, null, function* () {
          var _a4, _b3, _c3;
          try {
            let screenshotData;
            if (selector) {
              console.log("[CDP 截图] 截取元素:", selector);
              screenshotData = yield this._captureElement(session, selector, format2, quality);
            } else if (fullPage) {
              console.log("[CDP 截图] 截取整页");
              screenshotData = yield this._captureFullPage(session, format2, quality);
            } else {
              console.log("[CDP 截图] 截取可见区域");
              screenshotData = yield this._captureViewport(session, format2, quality);
            }
            const dataUrl = `data:image/${format2};base64,${screenshotData}`;
            console.log("[CDP 截图] 处理图片");
            const outputMode = IMAGE_TYPE || "upload";
            const processOptions = ImageProcessor.getDefaultOptions(outputMode);
            if (outputMode === "upload") ;
            const processor = new ImageProcessor();
            const processResult = yield processor.process(dataUrl, processOptions);
            if (!processResult.success) {
              throw new Error(processResult.error || "Image processing failed");
            }
            if (outputMode === "base64") {
              return multiContent(
                [
                  {
                    type: "image",
                    data: processResult.base64,
                    mimeType: processResult.mimeType
                  }
                ],
                {
                  format: (_a4 = processResult.mimeType) == null ? void 0 : _a4.split("/")[1],
                  width: (_b3 = processResult.dimensions) == null ? void 0 : _b3.width,
                  height: (_c3 = processResult.dimensions) == null ? void 0 : _c3.height
                }
              );
            }
          } catch (err) {
            console.error("[CDP 截图] 错误:", err);
            return error$J(
              `截图失败: ${err instanceof Error ? err.message : String(err)}`,
              err instanceof Error && err.name ? err.name : "EXECUTION_FAILED",
              {
                tab: targetTab,
                input: args,
                stack: err instanceof Error ? err.stack : void 0
              }
            );
          }
        }));
      });
    }
    /**
     * 截取可见区域
     */
    _captureViewport(session, format2, quality) {
      return __async(this, null, function* () {
        const result2 = yield session.send("Page.captureScreenshot", {
          format: format2,
          quality: format2 === "png" ? void 0 : quality,
          captureBeyondViewport: false
        });
        return result2.data;
      });
    }
    /**
     * 截取整个页面
     */
    _captureFullPage(session, format2, quality) {
      return __async(this, null, function* () {
        const layoutMetrics = yield session.send("Page.getLayoutMetrics", {});
        const { contentSize } = layoutMetrics;
        console.log("[CDP 截图] 页面尺寸:", contentSize);
        const result2 = yield session.send("Page.captureScreenshot", {
          format: format2,
          quality: format2 === "png" ? void 0 : quality,
          captureBeyondViewport: true,
          clip: {
            x: 0,
            y: 0,
            width: contentSize.width,
            height: contentSize.height,
            scale: 1
          }
        });
        return result2.data;
      });
    }
    /**
     * 截取特定元素
     */
    _captureElement(session, selector, format2, quality) {
      return __async(this, null, function* () {
        var _a3;
        const getElementRectExpression = `
      (function() {
        const element = document.querySelector(${JSON.stringify(selector)});
        if (!element) return { error: 'Element not found' };

        const rect = element.getBoundingClientRect();

        // 获取元素相对于文档的位置
        const scrollX = window.pageXOffset || document.documentElement.scrollLeft;
        const scrollY = window.pageYOffset || document.documentElement.scrollTop;

        return {
          x: rect.left + scrollX,
          y: rect.top + scrollY,
          width: rect.width,
          height: rect.height,
          viewportX: rect.left,
          viewportY: rect.top,
        };
      })()
    `;
        const elementResult = yield session.send("Runtime.evaluate", {
          expression: getElementRectExpression,
          returnByValue: true
        });
        const elementRect = (_a3 = elementResult == null ? void 0 : elementResult.result) == null ? void 0 : _a3.value;
        if (elementRect == null ? void 0 : elementRect.error) {
          throw new Error(`Element error: ${elementRect.error}`);
        }
        if (!elementRect) {
          throw new Error(`Element with selector "${selector}" not found`);
        }
        console.log("[CDP 截图] 元素位置:", elementRect);
        const result2 = yield session.send("Page.captureScreenshot", {
          format: format2,
          quality: format2 === "png" ? void 0 : quality,
          captureBeyondViewport: true,
          clip: {
            x: elementRect.x,
            y: elementRect.y,
            width: elementRect.width,
            height: elementRect.height,
            scale: 1
          }
        });
        return result2.data;
      });
    }
  }
  const screenshotTool = new ScreenshotTool();
  const fileUploadToolSchema = {
    sourceType: _enum$1(["url", "base64"]).default("base64").describe("Source type of the file: url (from web), base64 (encoded data)"),
    url: string$1().optional().describe('URL of the file to upload (required when sourceType is "url")'),
    base64Data: string$1().optional().describe('Base64 encoded file data (required when sourceType is "base64")'),
    filename: string$1().optional().describe("Name of the file (optional, will be inferred from URL or default)"),
    mimeType: string$1().optional().describe("MIME type of the file (optional, will be inferred from filename or content)"),
    inputSelector: string$1().optional().default('input[type="file"]').describe(
      'CSS selector for the file input element (alternative to uid, default: input[type="file"])'
    ),
    uid: string$1().optional().describe(
      'Unique ID from accessibility tree snapshot (alternative to inputSelector). Get this from chrome_accessibility_snapshot_cdp tool. Example: "1_42"'
    ),
    timeout: number$1().positive().default(3e4).describe("Timeout in milliseconds for upload operations (default: 30000)"),
    multiple: boolean$1().default(false).describe("Whether to upload multiple files (default: false)"),
    files: array(
      object({
        sourceType: _enum$1(["url", "base64"]).describe("Source type: url or base64"),
        url: string$1().optional().describe("URL of the file"),
        base64Data: string$1().optional().describe("Base64 encoded file data"),
        filename: string$1().optional().describe("Name of the file"),
        mimeType: string$1().optional().describe("MIME type of the file")
      })
    ).optional().describe("Array of files for multiple upload (used when multiple is true)"),
    dropZoneSelector: string$1().optional().describe("CSS selector for drag-and-drop zone (alternative to input selector)"),
    waitForComplete: boolean$1().default(false).describe("Wait for upload completion and monitor status (default: false)"),
    successSelectors: array(string$1()).optional().describe("CSS selectors to detect successful upload (used with waitForComplete)"),
    errorSelectors: array(string$1()).optional().describe("CSS selectors to detect upload errors (used with waitForComplete)"),
    tabId: number$1().int().positive().optional().describe("Target tab ID (optional)"),
    showVisual: boolean$1().default(true).describe("Show visual feedback of mouse movements and clicks (default: true)")
  };
  class FileUploadToolCDP extends BaseBrowserToolExecutor {
    constructor() {
      super(...arguments);
      __publicField2(this, "name", TOOL_NAMES.BROWSER.INPUT_UPLOAD_FILE);
      __publicField2(this, "description", "Upload files to web page file input elements using CSS selector or UID from accessibility snapshot. RECOMMENDED: Use chrome_accessibility_snapshot_cdp to locate file inputs reliably. Supports URL and base64 sources, multiple files, and drag-and-drop zones. More reliable than the standard upload tool.");
      __publicField2(this, "annotations", {
        title: "Upload File",
        category: ToolCategory.INPUT,
        readOnlyHint: false
      });
      __publicField2(this, "schema", fileUploadToolSchema);
    }
    /**
     * 执行文件上传操作
     */
    execute(args) {
      return __async(this, null, function* () {
        var _a3, _b2, _c2, _d2;
        console.log(`开始执行 CDP 文件上传操作，原始参数:`, args);
        const validationResult = this.validateArgs(args);
        if (!validationResult.success) {
          return validationResult.error;
        }
        const {
          sourceType,
          url: url2,
          filename,
          mimeType,
          base64Data,
          inputSelector,
          uid,
          timeout,
          multiple,
          files,
          dropZoneSelector,
          waitForComplete,
          successSelectors,
          errorSelectors,
          tabId,
          showVisual
        } = validationResult.data;
        console.log(`参数验证通过，处理后的参数:`, validationResult.data);
        try {
          const targetTab = yield cdpDebuggerManager.getTargetTab(tabId);
          const targetTabId = targetTab.id;
          if (((_a3 = targetTab.url) == null ? void 0 : _a3.startsWith("chrome://")) || ((_b2 = targetTab.url) == null ? void 0 : _b2.startsWith("edge://")) || ((_c2 = targetTab.url) == null ? void 0 : _c2.startsWith("https://chrome.google.com/webstore")) || ((_d2 = targetTab.url) == null ? void 0 : _d2.startsWith("https://microsoftedge.microsoft.com/"))) {
            return error$J(
              "Cannot upload files to special browser pages or web store pages due to security restrictions.",
              "INVALID_PARAMETERS",
              {}
            );
          }
          return yield cdpSessionExecutor.executeWithSession(targetTabId, (session, viewport) => __async(this, null, function* () {
            let result2;
            if (multiple && files) {
              result2 = yield this._uploadMultipleFiles(
                targetTabId,
                files,
                inputSelector,
                uid,
                timeout,
                showVisual
              );
            } else if (dropZoneSelector) {
              result2 = yield this._uploadByDragDrop(targetTabId, {
                sourceType,
                url: url2,
                base64Data,
                filename,
                mimeType,
                files,
                dropZoneSelector,
                showVisual
              });
            } else {
              result2 = yield this._uploadSingleFile(targetTabId, {
                sourceType,
                url: url2,
                base64Data,
                filename,
                mimeType,
                inputSelector,
                uid,
                timeout,
                showVisual
              });
            }
            if (waitForComplete) {
              const uploadResult = yield this._waitForUploadComplete(
                targetTabId,
                successSelectors,
                errorSelectors,
                timeout
              );
              result2 = __spreadProps(__spreadValues({}, result2), { uploadStatus: uploadResult });
            }
            const uploadMethod = multiple ? "multiple" : dropZoneSelector ? "dragdrop" : "single";
            const fileCount = multiple && files ? files.length : 1;
            return success$1(`Uploaded ${fileCount} file(s)`, __spreadValues({
              method: uploadMethod,
              files: result2.files || [{ name: filename, size: result2.size, type: mimeType }]
            }, result2));
          }));
        } catch (err) {
          console.error("CDP 文件上传操作错误:", err);
          return error$J(
            `执行文件上传时出错: ${err instanceof Error ? err.message : String(err)}`,
            err instanceof Error && err.message.includes("No active tab") ? "NO_ACTIVE_TAB" : "EXECUTION_ERROR",
            {
              stack: err instanceof Error ? err.stack : void 0
            }
          );
        }
      });
    }
    /**
     * 上传单个文件
     * 使用 CDP 底层能力：
     * 1. DOM.resolveNode 获取 DOM 节点
     * 2. DOM.setFileInputFiles 直接设置文件（绕过 JavaScript）
     * 3. Input.dispatchMouseEvent 模拟真实鼠标点击
     */
    _uploadSingleFile(tabId, params) {
      return __async(this, null, function* () {
        var _a3;
        const {
          sourceType,
          url: url2,
          base64Data,
          filename,
          mimeType,
          inputSelector,
          uid,
          showVisual = true
        } = params;
        let elementInfo;
        if (uid) {
          const backendNodeId = getBackendNodeIdByUid(uid);
          if (!backendNodeId) {
            throw new Error(`File input element not found for UID "${uid}"`);
          }
          console.log("[CDP 文件上传] 通过UID定位文件输入框:", uid, "→ backendNodeId:", backendNodeId);
          yield cdpScrollHelper.scrollElementByBackendNodeIdToCenter(tabId, backendNodeId);
          const position = yield cdpElementHelper.getElementByBackendNodeId(tabId, backendNodeId);
          if ("error" in position) {
            throw new Error(`Failed to get element position: ${position.error}`);
          }
          elementInfo = {
            centerX: position.centerX,
            centerY: position.centerY
          };
        } else if (inputSelector) {
          elementInfo = yield this._getFileInputElement(tabId, inputSelector);
          if (elementInfo.error) {
            throw new Error(
              `File input element error: ${elementInfo.error}. Selector: "${inputSelector}"`
            );
          }
        } else {
          throw new Error("Must provide either inputSelector or uid");
        }
        let fileData;
        let finalFilename;
        let finalMimeType;
        if (sourceType === "url" && url2) {
          const downloadResult = yield this._downloadFileFromUrl(url2);
          fileData = downloadResult.base64Data;
          finalFilename = filename || downloadResult.filename || "file";
          finalMimeType = mimeType || downloadResult.mimeType || "application/octet-stream";
        } else if (sourceType === "base64" && base64Data) {
          fileData = base64Data;
          finalFilename = filename || "file";
          finalMimeType = mimeType || "application/octet-stream";
        } else {
          throw new Error(`Invalid file source: sourceType=${sourceType}`);
        }
        try {
          if (showVisual) {
            const clickX = elementInfo.centerX;
            const clickY = elementInfo.centerY;
            yield this._showVisualFeedback(tabId, clickX, clickY, "click");
            yield new Promise((resolve2) => setTimeout(resolve2, 800));
            yield this._clearVisualFeedback(tabId);
          }
          console.log("[CDP 文件上传] 开始设置文件到输入框");
          const setFileExpression = `
        (function() {
          const element = document.querySelector(${JSON.stringify(inputSelector)});
          if (!element) return { error: 'Element not found' };
          
          // 触发 click 事件（只触发 JS 监听器，不会弹出系统对话框）
          element.dispatchEvent(new MouseEvent('click', { 
            bubbles: true, 
            cancelable: true,
            view: window 
          }));
          
          // 将 base64 转换为 Blob
          const base64Data = ${JSON.stringify(fileData)};
          const byteCharacters = atob(base64Data.includes(',') ? base64Data.split(',')[1] : base64Data);
          const byteNumbers = new Array(byteCharacters.length);
          for (let i = 0; i < byteCharacters.length; i++) {
            byteNumbers[i] = byteCharacters.charCodeAt(i);
          }
          const byteArray = new Uint8Array(byteNumbers);
          const blob = new Blob([byteArray], { type: ${JSON.stringify(finalMimeType)} });
          
          // 创建 File 对象
          const file = new File([blob], ${JSON.stringify(finalFilename)}, { type: ${JSON.stringify(finalMimeType)} });
          
          // 创建 DataTransfer 对象并设置文件
          const dataTransfer = new DataTransfer();
          dataTransfer.items.add(file);
          element.files = dataTransfer.files;
          
          // 触发 change 和 input 事件
          element.dispatchEvent(new Event('change', { bubbles: true }));
          element.dispatchEvent(new Event('input', { bubbles: true }));
          
          return {
            success: true,
            filename: file.name,
            size: file.size,
            type: file.type,
            filesCount: element.files.length,
          };
        })()
      `;
          const setFileResult = yield cdpDebuggerManager.sendCommand(tabId, "Runtime.evaluate", {
            expression: setFileExpression,
            returnByValue: true
          });
          const setFileValue = (_a3 = setFileResult == null ? void 0 : setFileResult.result) == null ? void 0 : _a3.value;
          if (setFileValue == null ? void 0 : setFileValue.error) {
            throw new Error(`Failed to set file: ${setFileValue.error}`);
          }
          console.log("[CDP 文件上传] 文件已设置:", setFileValue);
          return {
            method: "single",
            filename: finalFilename,
            size: setFileValue == null ? void 0 : setFileValue.size,
            type: finalMimeType,
            filesCount: (setFileValue == null ? void 0 : setFileValue.filesCount) || 1
          };
        } catch (error2) {
          console.error("[CDP 文件上传] 设置文件失败:", error2);
          throw error2;
        }
      });
    }
    /**
     * 显示可视化鼠标指针和轨迹
     */
    _showVisualFeedback(tabId, x, y, action) {
      return __async(this, null, function* () {
        const visualExpression = `
      (function() {
        // 创建或获取鼠标指针元素
        let cursor = document.getElementById('cdp-visual-cursor');
        if (!cursor) {
          cursor = document.createElement('div');
          cursor.id = 'cdp-visual-cursor';
          cursor.style.cssText = \`
            position: fixed;
            width: 20px;
            height: 20px;
            border: 2px solid #ff0000;
            border-radius: 50%;
            background: rgba(255, 0, 0, 0.3);
            pointer-events: none;
            z-index: 999999;
            transition: all 0.1s ease;
            box-shadow: 0 0 10px rgba(255, 0, 0, 0.5);
          \`;
          document.body.appendChild(cursor);
        }
        
        // 更新位置
        cursor.style.left = (${x} - 10) + 'px';
        cursor.style.top = (${y} - 10) + 'px';
        
        // 根据动作改变样式
        if (${JSON.stringify(action)} === 'click') {
          cursor.style.background = 'rgba(255, 0, 0, 0.8)';
          cursor.style.transform = 'scale(0.8)';
          setTimeout(() => {
            cursor.style.background = 'rgba(255, 0, 0, 0.3)';
            cursor.style.transform = 'scale(1)';
          }, 100);
        } else if (${JSON.stringify(action)} === 'drag') {
          cursor.style.background = 'rgba(0, 255, 0, 0.5)';
          cursor.style.borderColor = '#00ff00';
        } else if (${JSON.stringify(action)} === 'release') {
          cursor.style.background = 'rgba(255, 0, 0, 0.3)';
          cursor.style.borderColor = '#ff0000';
        }
        
        // 创建轨迹点
        const trail = document.createElement('div');
        trail.className = 'cdp-cursor-trail';
        trail.style.cssText = \`
          position: fixed;
          width: 6px;
          height: 6px;
          border-radius: 50%;
          background: rgba(255, 0, 0, 0.6);
          pointer-events: none;
          z-index: 999998;
          left: \${${x} - 3}px;
          top: \${${y} - 3}px;
        \`;
        document.body.appendChild(trail);
        
        // 3秒后移除轨迹点
        setTimeout(() => {
          trail.style.opacity = '0';
          trail.style.transition = 'opacity 0.5s';
          setTimeout(() => trail.remove(), 500);
        }, 3000);
        
        return { success: true };
      })()
    `;
        try {
          yield cdpDebuggerManager.sendCommand(tabId, "Runtime.evaluate", {
            expression: visualExpression,
            returnByValue: true
          });
        } catch (error2) {
          console.warn("[CDP 可视化] 显示视觉反馈失败:", error2);
        }
      });
    }
    /**
     * 清除可视化元素
     */
    _clearVisualFeedback(tabId) {
      return __async(this, null, function* () {
        const clearExpression = `
      (function() {
        const cursor = document.getElementById('cdp-visual-cursor');
        if (cursor) cursor.remove();
        
        const trails = document.querySelectorAll('.cdp-cursor-trail');
        trails.forEach(trail => trail.remove());
        
        return { success: true };
      })()
    `;
        try {
          yield cdpDebuggerManager.sendCommand(tabId, "Runtime.evaluate", {
            expression: clearExpression,
            returnByValue: true
          });
        } catch (error2) {
          console.warn("[CDP 可视化] 清除视觉反馈失败:", error2);
        }
      });
    }
    /**
     * 获取文件输入框元素信息
     * 使用 CDP DOM API 获取元素的详细信息
     */
    _getFileInputElement(tabId, selector) {
      return __async(this, null, function* () {
        var _a3;
        const getElementExpression = `
      (function() {
        const element = document.querySelector(${JSON.stringify(selector)});
        if (!element) return { error: 'Element not found' };
        
        // 检查是否是文件输入框
        if (element.tagName !== 'INPUT' || element.type !== 'file') {
          return { error: 'Element is not a file input' };
        }
        
        // 检查可见性(仅作为状态信息,不阻止操作)
        const style = window.getComputedStyle(element);
        const isVisible = style.display !== 'none' && 
                         style.visibility !== 'hidden' && 
                         style.opacity !== '0';
        
        const rect = element.getBoundingClientRect();
        
        return {
          tagName: element.tagName,
          type: element.type,
          isVisible: isVisible,
          isHidden: !isVisible,
          centerX: rect.left + rect.width / 2,
          centerY: rect.top + rect.height / 2,
          rect: {
            x: rect.x,
            y: rect.y,
            width: rect.width,
            height: rect.height,
          },
        };
      })()
    `;
        const result2 = yield cdpDebuggerManager.sendCommand(tabId, "Runtime.evaluate", {
          expression: getElementExpression,
          returnByValue: true
        });
        return ((_a3 = result2 == null ? void 0 : result2.result) == null ? void 0 : _a3.value) || { error: "Failed to get element info" };
      });
    }
    /**
     * 上传多个文件
     */
    _uploadMultipleFiles(tabId, files, inputSelector, uid, timeout = 3e4, showVisual = true) {
      return __async(this, null, function* () {
        var _a3;
        if (!files || files.length === 0) {
          throw new Error("Files array is required for multiple upload");
        }
        let elementInfo;
        if (uid) {
          const backendNodeId = getBackendNodeIdByUid(uid);
          if (!backendNodeId) {
            throw new Error(`File input element not found for UID "${uid}"`);
          }
          console.log(
            "[CDP 多文件上传] 通过UID定位文件输入框:",
            uid,
            "→ backendNodeId:",
            backendNodeId
          );
          yield cdpScrollHelper.scrollElementByBackendNodeIdToCenter(tabId, backendNodeId);
          const position = yield cdpElementHelper.getElementByBackendNodeId(tabId, backendNodeId);
          if ("error" in position) {
            throw new Error(`Failed to get element position: ${position.error}`);
          }
          elementInfo = {
            centerX: position.centerX,
            centerY: position.centerY
          };
        } else if (inputSelector) {
          elementInfo = yield this._getFileInputElement(tabId, inputSelector);
          if (elementInfo.error) {
            throw new Error(
              `File input element error: ${elementInfo.error}. Selector: "${inputSelector}"`
            );
          }
        } else {
          throw new Error("Must provide either inputSelector or uid");
        }
        const fileDataList = [];
        for (const file2 of files) {
          let fileData;
          let finalFilename;
          let finalMimeType;
          if (file2.sourceType === "url" && file2.url) {
            const downloadResult = yield this._downloadFileFromUrl(file2.url);
            fileData = downloadResult.base64Data;
            finalFilename = file2.filename || downloadResult.filename || "file";
            finalMimeType = file2.mimeType || downloadResult.mimeType || "application/octet-stream";
          } else if (file2.sourceType === "base64" && file2.base64Data) {
            fileData = file2.base64Data;
            finalFilename = file2.filename || "file";
            finalMimeType = file2.mimeType || "application/octet-stream";
          } else {
            console.warn(`Skipping invalid file:`, file2);
            continue;
          }
          fileDataList.push({
            base64Data: fileData,
            filename: finalFilename,
            mimeType: finalMimeType
          });
        }
        if (showVisual && "centerX" in elementInfo && "centerY" in elementInfo) {
          const clickX = elementInfo.centerX;
          const clickY = elementInfo.centerY;
          yield this._showVisualFeedback(tabId, clickX, clickY, "click");
          yield new Promise((resolve2) => setTimeout(resolve2, 800));
          yield this._clearVisualFeedback(tabId);
        }
        console.log("[CDP 多文件上传] 开始设置多个文件到输入框");
        const setFilesExpression = `
      (function() {
        const element = document.querySelector(${JSON.stringify(inputSelector)});
        if (!element) return { error: 'Element not found' };
        
        if (element.tagName !== 'INPUT' || element.type !== 'file') {
          return { error: 'Element is not a file input' };
        }
        
        if (!element.multiple) {
          return { error: 'File input does not support multiple files' };
        }
        
        // 触发 click 事件（只触发 JS 监听器，不会弹出系统对话框）
        element.dispatchEvent(new MouseEvent('click', { 
          bubbles: true, 
          cancelable: true,
          view: window 
        }));
        
        const filesData = ${JSON.stringify(fileDataList)};
        const dataTransfer = new DataTransfer();
        
        for (const fileData of filesData) {
          const base64Data = fileData.base64Data;
          const byteCharacters = atob(base64Data.includes(',') ? base64Data.split(',')[1] : base64Data);
          const byteNumbers = new Array(byteCharacters.length);
          for (let i = 0; i < byteCharacters.length; i++) {
            byteNumbers[i] = byteCharacters.charCodeAt(i);
          }
          const byteArray = new Uint8Array(byteNumbers);
          const blob = new Blob([byteArray], { type: fileData.mimeType });
          const file = new File([blob], fileData.filename, { type: fileData.mimeType });
          dataTransfer.items.add(file);
        }
        
        element.files = dataTransfer.files;
        
        // 触发事件
        element.dispatchEvent(new Event('change', { bubbles: true }));
        element.dispatchEvent(new Event('input', { bubbles: true }));
        
        return {
          success: true,
          filesCount: element.files.length,
          files: Array.from(element.files).map(f => ({
            name: f.name,
            size: f.size,
            type: f.type,
          })),
        };
      })()
    `;
        const setFilesResult = yield cdpDebuggerManager.sendCommand(tabId, "Runtime.evaluate", {
          expression: setFilesExpression,
          returnByValue: true
        });
        const setFilesValue = (_a3 = setFilesResult == null ? void 0 : setFilesResult.result) == null ? void 0 : _a3.value;
        if (setFilesValue == null ? void 0 : setFilesValue.error) {
          throw new Error(`Failed to set files: ${setFilesValue.error}`);
        }
        console.log("[CDP 文件上传] 多个文件已设置:", setFilesValue);
        return {
          method: "multiple",
          filesCount: (setFilesValue == null ? void 0 : setFilesValue.filesCount) || 0,
          files: (setFilesValue == null ? void 0 : setFilesValue.files) || []
        };
      });
    }
    /**
     * 拖拽上传
     * 使用 CDP 底层能力模拟真实的拖拽操作：
     * 1. Input.dispatchMouseEvent 模拟鼠标移动和拖拽
     * 2. Input.dispatchDragEvent 模拟拖拽事件（如果支持）
     * 3. 模拟完整的拖拽事件序列
     */
    _uploadByDragDrop(tabId, params) {
      return __async(this, null, function* () {
        var _a3;
        const { dropZoneSelector, files: multipleFiles, showVisual = true } = params;
        const dropZoneInfo = yield this._getDropZoneElement(tabId, dropZoneSelector);
        if (dropZoneInfo.error) {
          throw new Error(
            `Drop zone element error: ${dropZoneInfo.error}. Selector: "${dropZoneSelector}"`
          );
        }
        const fileDataList = [];
        if (multipleFiles && multipleFiles.length > 0) {
          for (const file2 of multipleFiles) {
            let fileData;
            let finalFilename;
            let finalMimeType;
            if (file2.sourceType === "url" && file2.url) {
              const downloadResult = yield this._downloadFileFromUrl(file2.url);
              fileData = downloadResult.base64Data;
              finalFilename = file2.filename || downloadResult.filename || "file";
              finalMimeType = file2.mimeType || downloadResult.mimeType || "application/octet-stream";
            } else if (file2.sourceType === "base64" && file2.base64Data) {
              fileData = file2.base64Data;
              finalFilename = file2.filename || "file";
              finalMimeType = file2.mimeType || "application/octet-stream";
            } else {
              continue;
            }
            fileDataList.push({
              base64Data: fileData,
              filename: finalFilename,
              mimeType: finalMimeType
            });
          }
        } else {
          let fileData;
          let finalFilename;
          let finalMimeType;
          if (params.sourceType === "url" && params.url) {
            const downloadResult = yield this._downloadFileFromUrl(params.url);
            fileData = downloadResult.base64Data;
            finalFilename = params.filename || downloadResult.filename || "file";
            finalMimeType = params.mimeType || downloadResult.mimeType || "application/octet-stream";
          } else if (params.sourceType === "base64" && params.base64Data) {
            fileData = params.base64Data;
            finalFilename = params.filename || "file";
            finalMimeType = params.mimeType || "application/octet-stream";
          } else {
            throw new Error("Invalid file source for drag drop");
          }
          fileDataList.push({
            base64Data: fileData,
            filename: finalFilename,
            mimeType: finalMimeType
          });
        }
        const dropX = dropZoneInfo.centerX;
        const dropY = dropZoneInfo.centerY;
        console.log("[CDP 文件上传] 开始模拟拖拽操作到:", { dropX, dropY });
        const startX = dropX - 100;
        const startY = dropY - 100;
        if (showVisual) yield this._showVisualFeedback(tabId, startX, startY, "move");
        yield cdpDebuggerManager.sendCommand(tabId, "Input.dispatchMouseEvent", {
          type: "mouseMoved",
          x: startX,
          y: startY
        });
        yield new Promise((resolve2) => setTimeout(resolve2, showVisual ? 300 : 50));
        if (showVisual) yield this._showVisualFeedback(tabId, startX, startY, "drag");
        yield cdpDebuggerManager.sendCommand(tabId, "Input.dispatchMouseEvent", {
          type: "mousePressed",
          x: startX,
          y: startY,
          button: "left",
          clickCount: 1
        });
        yield new Promise((resolve2) => setTimeout(resolve2, showVisual ? 300 : 100));
        const steps = showVisual ? 8 : 5;
        for (let i2 = 1; i2 <= steps; i2++) {
          const currentX = startX + (dropX - startX) * i2 / steps;
          const currentY = startY + (dropY - startY) * i2 / steps;
          if (showVisual) yield this._showVisualFeedback(tabId, currentX, currentY, "drag");
          yield cdpDebuggerManager.sendCommand(tabId, "Input.dispatchMouseEvent", {
            type: "mouseMoved",
            x: currentX,
            y: currentY,
            button: "left"
          });
          yield new Promise((resolve2) => setTimeout(resolve2, showVisual ? 150 : 30));
        }
        console.log("[CDP 文件上传] 鼠标拖拽到目标位置");
        yield new Promise((resolve2) => setTimeout(resolve2, 100));
        const prepareFilesExpression = `
      (function() {
        const element = document.querySelector(${JSON.stringify(dropZoneSelector)});
        if (!element) return { error: 'Drop zone element not found' };
        
        const filesData = ${JSON.stringify(fileDataList)};
        const dataTransfer = new DataTransfer();
        
        for (const fileData of filesData) {
          const base64Data = fileData.base64Data;
          const byteCharacters = atob(base64Data.includes(',') ? base64Data.split(',')[1] : base64Data);
          const byteNumbers = new Array(byteCharacters.length);
          for (let i = 0; i < byteCharacters.length; i++) {
            byteNumbers[i] = byteCharacters.charCodeAt(i);
          }
          const byteArray = new Uint8Array(byteNumbers);
          const blob = new Blob([byteArray], { type: fileData.mimeType });
          const file = new File([blob], fileData.filename, { type: fileData.mimeType });
          dataTransfer.items.add(file);
        }
        
        // 触发拖拽事件序列
        const rect = element.getBoundingClientRect();
        const x = rect.left + rect.width / 2;
        const y = rect.top + rect.height / 2;
        
        const dragEnterEvent = new DragEvent('dragenter', {
          bubbles: true,
          cancelable: true,
          dataTransfer: dataTransfer,
          clientX: x,
          clientY: y,
        });
        element.dispatchEvent(dragEnterEvent);
        
        const dragOverEvent = new DragEvent('dragover', {
          bubbles: true,
          cancelable: true,
          dataTransfer: dataTransfer,
          clientX: x,
          clientY: y,
        });
        element.dispatchEvent(dragOverEvent);
        
        const dropEvent = new DragEvent('drop', {
          bubbles: true,
          cancelable: true,
          dataTransfer: dataTransfer,
          clientX: x,
          clientY: y,
        });
        element.dispatchEvent(dropEvent);
        
        return {
          success: true,
          filesCount: dataTransfer.files.length,
          files: Array.from(dataTransfer.files).map(f => ({
            name: f.name,
            size: f.size,
            type: f.type,
          })),
        };
      })()
    `;
        const prepareResult = yield cdpDebuggerManager.sendCommand(tabId, "Runtime.evaluate", {
          expression: prepareFilesExpression,
          returnByValue: true
        });
        const prepareValue = (_a3 = prepareResult == null ? void 0 : prepareResult.result) == null ? void 0 : _a3.value;
        if (prepareValue == null ? void 0 : prepareValue.error) {
          throw new Error(`Failed to prepare files for drag drop: ${prepareValue.error}`);
        }
        yield new Promise((resolve2) => setTimeout(resolve2, showVisual ? 300 : 100));
        if (showVisual) yield this._showVisualFeedback(tabId, dropX, dropY, "release");
        yield cdpDebuggerManager.sendCommand(tabId, "Input.dispatchMouseEvent", {
          type: "mouseReleased",
          x: dropX,
          y: dropY,
          button: "left",
          clickCount: 1
        });
        console.log("[CDP 文件上传] 鼠标释放，拖拽完成");
        yield new Promise((resolve2) => setTimeout(resolve2, showVisual ? 500 : 100));
        if (showVisual) yield this._clearVisualFeedback(tabId);
        console.log("[CDP 文件上传] 拖拽上传已完成:", prepareValue);
        return {
          method: "dragdrop",
          filesCount: (prepareValue == null ? void 0 : prepareValue.filesCount) || 0,
          files: (prepareValue == null ? void 0 : prepareValue.files) || []
        };
      });
    }
    /**
     * 获取拖拽区域元素信息
     */
    _getDropZoneElement(tabId, selector) {
      return __async(this, null, function* () {
        var _a3;
        const getElementExpression = `
      (function() {
        const element = document.querySelector(${JSON.stringify(selector)});
        if (!element) return { error: 'Element not found' };
        
        // 检查可见性
        const style = window.getComputedStyle(element);
        const isVisible = style.display !== 'none' && 
                         style.visibility !== 'hidden' && 
                         style.opacity !== '0';
        
        if (!isVisible) {
          return { error: 'Element is not visible' };
        }
        
        const rect = element.getBoundingClientRect();
        
        return {
          tagName: element.tagName,
          isVisible: true,
          centerX: rect.left + rect.width / 2,
          centerY: rect.top + rect.height / 2,
          rect: {
            x: rect.x,
            y: rect.y,
            width: rect.width,
            height: rect.height,
          },
        };
      })()
    `;
        const result2 = yield cdpDebuggerManager.sendCommand(tabId, "Runtime.evaluate", {
          expression: getElementExpression,
          returnByValue: true
        });
        return ((_a3 = result2 == null ? void 0 : result2.result) == null ? void 0 : _a3.value) || { error: "Failed to get element info" };
      });
    }
    /**
     * 等待上传完成
     */
    _waitForUploadComplete(tabId, successSelectors, errorSelectors, timeout = 3e4) {
      return __async(this, null, function* () {
        var _a3;
        const defaultSuccessSelectors = [
          ".upload-success",
          ".success",
          '[class*="success"]',
          '[data-status="success"]'
        ];
        const defaultErrorSelectors = [
          ".upload-error",
          ".error",
          '[class*="error"]',
          '[data-status="error"]'
        ];
        const finalSuccessSelectors = successSelectors || defaultSuccessSelectors;
        const finalErrorSelectors = errorSelectors || defaultErrorSelectors;
        const waitExpression = `
      new Promise((resolve) => {
        const startTime = Date.now();
        const timeout = ${timeout};
        
        const checkStatus = () => {
          // 检查成功标识
          const successSelectors = ${JSON.stringify(finalSuccessSelectors)};
          for (const selector of successSelectors) {
            const element = document.querySelector(selector);
            if (element && window.getComputedStyle(element).display !== 'none') {
              resolve({
                status: 'success',
                selector: selector,
                text: element.textContent,
                elapsed: Date.now() - startTime,
              });
              return;
            }
          }
          
          // 检查错误标识
          const errorSelectors = ${JSON.stringify(finalErrorSelectors)};
          for (const selector of errorSelectors) {
            const element = document.querySelector(selector);
            if (element && window.getComputedStyle(element).display !== 'none') {
              resolve({
                status: 'error',
                selector: selector,
                text: element.textContent,
                elapsed: Date.now() - startTime,
              });
              return;
            }
          }
          
          // 检查超时
          if (Date.now() - startTime > timeout) {
            resolve({
              status: 'timeout',
              elapsed: Date.now() - startTime,
            });
            return;
          }
          
          // 继续检查
          setTimeout(checkStatus, 500);
        };
        
        checkStatus();
      })
    `;
        const waitResult = yield cdpDebuggerManager.sendCommand(tabId, "Runtime.evaluate", {
          expression: waitExpression,
          awaitPromise: true,
          returnByValue: true
        });
        const waitValue = (_a3 = waitResult == null ? void 0 : waitResult.result) == null ? void 0 : _a3.value;
        console.log("[CDP 文件上传] 上传完成状态:", waitValue);
        return waitValue;
      });
    }
    /**
     * 从 URL 下载文件
     */
    _downloadFileFromUrl(url2) {
      return __async(this, null, function* () {
        try {
          const response = yield fetch(url2);
          if (!response.ok) {
            throw new Error(`Failed to download file: ${response.statusText}`);
          }
          const blob = yield response.blob();
          const arrayBuffer = yield blob.arrayBuffer();
          const uint8Array = new Uint8Array(arrayBuffer);
          let binary = "";
          for (let i2 = 0; i2 < uint8Array.length; i2++) {
            binary += String.fromCharCode(uint8Array[i2]);
          }
          const base64Data = btoa(binary);
          const urlObj = new URL(url2);
          const pathname = urlObj.pathname;
          const filename = pathname.substring(pathname.lastIndexOf("/") + 1) || "file";
          const mimeType = blob.type || "application/octet-stream";
          return {
            base64Data,
            filename,
            mimeType
          };
        } catch (error2) {
          throw new Error(
            `Failed to download file from URL: ${error2 instanceof Error ? error2.message : String(error2)}`
          );
        }
      });
    }
  }
  const fileUploadToolCDP = new FileUploadToolCDP();
  const waitForElementSchema = {
    selector: string$1().min(1).describe('CSS selector for the element to wait for (e.g., "#submit-button", ".modal")'),
    timeout: number$1().positive().default(1e4).describe("Timeout in milliseconds (default: 10000)"),
    visible: boolean$1().default(true).describe("Whether the element should be visible (default: true)"),
    tabId: number$1().int().positive().optional().describe("Target tab ID (optional)"),
    pollInterval: number$1().positive().default(100).describe("Polling interval in milliseconds (default: 100)"),
    useBinding: boolean$1().default(false).describe(
      "Use Runtime.addBinding for event-driven detection instead of polling (default: false)"
    )
  };
  class WaitForElementToolCDP extends BaseBrowserToolExecutor {
    constructor() {
      super(...arguments);
      __publicField2(this, "name", TOOL_NAMES.BROWSER.WAIT_FOR_ELEMENT);
      __publicField2(this, "description", "Wait for an element to appear on the page using CDP. Supports background polling without activating the tab, and optional event-driven detection with Runtime.addBinding.");
      __publicField2(this, "annotations", {
        title: "Wait for Element (CDP)",
        category: ToolCategory.DEBUGGING,
        readOnlyHint: true
      });
      __publicField2(this, "schema", waitForElementSchema);
    }
    /**
     * 执行等待元素操作
     */
    execute(args) {
      return __async(this, null, function* () {
        var _a3, _b2, _c2, _d2;
        console.log(`开始执行 CDP 等待元素操作，原始参数:`, args);
        const validationResult = this.validateArgs(args);
        if (!validationResult.success) {
          return validationResult.error;
        }
        const { selector, timeout, visible, tabId, pollInterval, useBinding } = validationResult.data;
        console.log(`参数验证通过，处理后的参数:`, validationResult.data);
        try {
          const targetTab = yield cdpDebuggerManager.getTargetTab(tabId);
          const targetTabId = targetTab.id;
          if (((_a3 = targetTab.url) == null ? void 0 : _a3.startsWith("chrome://")) || ((_b2 = targetTab.url) == null ? void 0 : _b2.startsWith("edge://")) || ((_c2 = targetTab.url) == null ? void 0 : _c2.startsWith("https://chrome.google.com/webstore")) || ((_d2 = targetTab.url) == null ? void 0 : _d2.startsWith("https://microsoftedge.microsoft.com/"))) {
            return error$J(
              "Cannot wait for elements on special browser pages or web store pages due to security restrictions.",
              "INVALID_PARAMETERS",
              {}
            );
          }
          return yield cdpSessionExecutor.executeWithSession(targetTabId, (session, viewport) => __async(this, null, function* () {
            let result2;
            if (useBinding) {
              result2 = yield this._waitWithBinding(targetTabId, selector, visible, timeout);
            } else {
              result2 = yield this._waitWithPolling(
                targetTabId,
                selector,
                visible,
                timeout,
                pollInterval
              );
            }
            if (!result2.found) {
              return error$J(`Element not found within timeout: ${selector}`, "TIMEOUT", {
                selector,
                timeout,
                timedOut: result2.timedOut
              });
            }
            return success$1(`Element appeared after ${result2.foundAt}ms`, {
              found: true,
              foundAt: result2.foundAt,
              elementInfo: result2.elementInfo,
              method: useBinding ? "binding" : "polling"
            });
          }));
        } catch (err) {
          console.error("CDP 等待元素操作错误:", err);
          return error$J(
            `执行等待元素时出错: ${err instanceof Error ? err.message : String(err)}`,
            err instanceof Error && err.message.includes("No active tab") ? "NO_ACTIVE_TAB" : "EXECUTION_ERROR",
            {
              stack: err instanceof Error ? err.stack : void 0
            }
          );
        }
      });
    }
    /**
     * 使用轮询方式等待元素
     * 通过 Runtime.evaluate 定期检查元素是否存在
     *
     * 优势：
     * - 不需要激活 tab
     * - 后台运行，不干扰用户
     * - 可以检测任何 CSS 选择器
     */
    _waitWithPolling(tabId, selector, visible, timeout, pollInterval) {
      return __async(this, null, function* () {
        var _a3;
        const startTime = Date.now();
        const endTime = startTime + timeout;
        console.log(`[CDP 等待元素] 开始轮询检查元素: ${selector}`);
        while (Date.now() < endTime) {
          const checkExpression = `
        (function() {
          const element = document.querySelector(${JSON.stringify(selector)});
          if (!element) return { found: false };
          
          ${visible ? `
          const style = window.getComputedStyle(element);
          const isVisible = style.display !== 'none' && 
                           style.visibility !== 'hidden' && 
                           style.opacity !== '0';
          
          if (!isVisible) return { found: false };
          ` : ""}
          
          const rect = element.getBoundingClientRect();
          
          return {
            found: true,
            elementInfo: {
              tagName: element.tagName,
              id: element.id,
              className: element.className,
              text: element.textContent?.trim().substring(0, 100) || '',
              href: element.href || null,
              type: element.type || null,
              isVisible: ${visible ? "true" : 'window.getComputedStyle(element).display !== "none"'},
              rect: {
                x: rect.x,
                y: rect.y,
                width: rect.width,
                height: rect.height,
                top: rect.top,
                right: rect.right,
                bottom: rect.bottom,
                left: rect.left,
              },
            },
          };
        })()
      `;
          try {
            const result2 = yield cdpDebuggerManager.sendCommand(tabId, "Runtime.evaluate", {
              expression: checkExpression,
              returnByValue: true
            });
            const value = (_a3 = result2 == null ? void 0 : result2.result) == null ? void 0 : _a3.value;
            if (value == null ? void 0 : value.found) {
              const foundAt = Date.now() - startTime;
              console.log(`[CDP 等待元素] 元素已找到，耗时: ${foundAt}ms`);
              return {
                found: true,
                foundAt,
                timedOut: false,
                elementInfo: value.elementInfo
              };
            }
          } catch (error2) {
            console.warn(`[CDP 等待元素] 检查元素时出错:`, error2);
          }
          yield new Promise((resolve2) => setTimeout(resolve2, pollInterval));
        }
        console.log(`[CDP 等待元素] 等待超时: ${selector}`);
        return {
          found: false,
          timedOut: true
        };
      });
    }
    /**
     * 使用 Runtime.addBinding 事件驱动方式等待元素
     * 在页面中注入监听器，当元素出现时立即通知
     *
     * 优势：
     * - 事件驱动，更高效
     * - 不需要轮询，减少 CPU 占用
     * - 可以监听 DOM 变化（MutationObserver）
     */
    _waitWithBinding(tabId, selector, visible, timeout) {
      return __async(this, null, function* () {
        const startTime = Date.now();
        const bindingName = `__mcpWaitForElement_${Date.now()}`;
        console.log(`[CDP 等待元素] 使用 Binding 方式等待元素: ${selector}`);
        let timeoutId;
        let bindingListener;
        const cleanup = () => __async(null, null, function* () {
          if (timeoutId) clearTimeout(timeoutId);
          if (bindingListener) {
            chrome.debugger.onEvent.removeListener(bindingListener);
          }
          try {
            yield cdpDebuggerManager.sendCommand(tabId, "Runtime.removeBinding", {
              name: bindingName
            });
          } catch (error2) {
            console.warn("[CDP 等待元素] 移除 binding 失败:", error2);
          }
        });
        try {
          yield cdpDebuggerManager.sendCommand(tabId, "Runtime.addBinding", {
            name: bindingName
          });
          const waitPromise = new Promise((resolve2) => {
            bindingListener = (source, method, params) => {
              if (source.tabId === tabId && method === "Runtime.bindingCalled" && (params == null ? void 0 : params.name) === bindingName) {
                const payload = JSON.parse(params.payload);
                const foundAt = Date.now() - startTime;
                console.log(`[CDP 等待元素] 元素已找到（事件驱动），耗时: ${foundAt}ms`);
                cleanup().then(() => {
                  resolve2({
                    found: true,
                    foundAt,
                    timedOut: false,
                    elementInfo: payload.elementInfo
                  });
                });
              }
            };
            chrome.debugger.onEvent.addListener(bindingListener);
            timeoutId = setTimeout(() => {
              console.log(`[CDP 等待元素] 等待超时（事件驱动）: ${selector}`);
              cleanup().then(() => {
                resolve2({
                  found: false,
                  timedOut: true
                });
              });
            }, timeout);
          });
          const monitorExpression = `
        (function() {
          const selector = ${JSON.stringify(selector)};
          const checkVisible = ${visible};
          const bindingName = ${JSON.stringify(bindingName)};
          
          // 检查元素的函数
          function checkElement() {
            const element = document.querySelector(selector);
            if (!element) return false;
            
            if (checkVisible) {
              const style = window.getComputedStyle(element);
              const isVisible = style.display !== 'none' && 
                               style.visibility !== 'hidden' && 
                               style.opacity !== '0';
              if (!isVisible) return false;
            }
            
            const rect = element.getBoundingClientRect();
            
            // 调用 binding 通知找到元素
            window[bindingName](JSON.stringify({
              elementInfo: {
                tagName: element.tagName,
                id: element.id,
                className: element.className,
                text: element.textContent?.trim().substring(0, 100) || '',
                href: element.href || null,
                type: element.type || null,
                isVisible: checkVisible,
                rect: {
                  x: rect.x,
                  y: rect.y,
                  width: rect.width,
                  height: rect.height,
                  top: rect.top,
                  right: rect.right,
                  bottom: rect.bottom,
                  left: rect.left,
                },
              },
            }));
            
            return true;
          }
          
          // 立即检查一次
          if (checkElement()) return;
          
          // 使用 MutationObserver 监听 DOM 变化
          const observer = new MutationObserver(() => {
            if (checkElement()) {
              observer.disconnect();
            }
          });
          
          observer.observe(document.body, {
            childList: true,
            subtree: true,
            attributes: checkVisible,
            attributeFilter: checkVisible ? ['style', 'class'] : undefined,
          });
          
          // 保存 observer 引用以便清理
          window.__mcpElementObserver = observer;
        })()
      `;
          yield cdpDebuggerManager.sendCommand(tabId, "Runtime.evaluate", {
            expression: monitorExpression,
            returnByValue: false
          });
          return yield waitPromise;
        } catch (error2) {
          yield cleanup();
          throw error2;
        }
      });
    }
  }
  const waitForElementToolCDP = new WaitForElementToolCDP();
  const getInteractiveElementsToolSchema = {
    textQuery: string$1().optional().describe(
      "Fuzzy text query using 3-layer fallback strategy. Mutually exclusive with selector and coordinates."
    ),
    selector: string$1().optional().describe(
      "CSS selector to directly query elements. Mutually exclusive with textQuery and coordinates."
    ),
    coordinates: object({
      x: number$1().optional().describe("X coordinate relative to viewport"),
      y: number$1().optional().describe("Y coordinate relative to viewport")
    }).optional().transform((val) => {
      if (!val || val.x === void 0 && val.y === void 0) {
        return void 0;
      }
      if (val.x === void 0 || val.y === void 0) {
        throw new Error("Both x and y coordinates must be provided");
      }
      return val;
    }).describe(
      "Point-based element query at specific coordinates. Mutually exclusive with textQuery and selector."
    ),
    tabId: number$1().int().positive().optional().describe("Target tab ID (optional, defaults to active tab)")
  };
  class GetInteractiveElementsToolCDP extends BaseBrowserToolExecutor {
    constructor() {
      super(...arguments);
      __publicField2(this, "name", TOOL_NAMES.BROWSER.GET_INTERACTIVE_ELEMENTS);
      __publicField2(this, "description", "⚠️ RECOMMENDED TOOL - Get interactive elements using CDP without activating the page. Supports textQuery for fuzzy text search. Returns a lightweight element list (uid, label, text, rect, etc.). Use this tool instead of the legacy chrome_get_interactive_elements when possible.");
      __publicField2(this, "annotations", {
        title: "Get Interactive Elements (CDP)",
        category: ToolCategory.DEBUGGING,
        readOnlyHint: true
      });
      __publicField2(this, "schema", getInteractiveElementsToolSchema);
      __publicField2(this, "snapshotCounter", 1);
    }
    /**
     * 执行工具(重构版,支持智能路由)
     */
    execute(args) {
      return __async(this, null, function* () {
        console.log("[GetInteractiveElements CDP] 开始执行,参数:", args);
        const validationResult = this.validateArgs(args);
        if (!validationResult.success) {
          return validationResult.error;
        }
        const { textQuery, selector, coordinates, tabId } = validationResult.data;
        const queryParamsCount = [
          textQuery !== void 0,
          selector !== void 0,
          coordinates !== void 0
        ].filter(Boolean).length;
        if (queryParamsCount > 1) {
          return error$J(
            "Only one query parameter is allowed: textQuery, selector, or coordinates",
            "INVALID_PARAMS",
            { input: args }
          );
        }
        try {
          console.log("[GetInteractiveElements CDP] 尝试获取 tab:", tabId);
          const targetTab = yield cdpDebuggerManager.getTargetTab(tabId, false);
          const targetTabId = targetTab.id;
          console.log("[GetInteractiveElements CDP] 成功获取 tab:", targetTabId, targetTab.url);
          if (this.isRestrictedUrl(targetTab.url)) {
            return error$J(
              "Cannot access special browser pages, web store pages, or extension pages",
              "EXECUTION_FAILED",
              {
                tab: targetTab,
                input: args
              }
            );
          }
          const result2 = yield cdpSessionExecutor.executeWithSession(
            targetTabId,
            (session, viewport) => __async(this, null, function* () {
              try {
                if (coordinates) {
                  console.log(
                    `[GetInteractiveElements CDP] 坐标查询: (${coordinates.x}, ${coordinates.y})`
                  );
                  const elements2 = yield cdpInteractiveElementsHelper.findElementsByCoordinates(
                    session,
                    coordinates.x,
                    coordinates.y,
                    { includeCoordinates: true }
                  );
                  return this.formatRuntimeResult(elements2, void 0, "coordinate");
                }
                if (selector) {
                  console.log(`[GetInteractiveElements CDP] Selector 查询: ${selector}`);
                  const elements2 = yield cdpInteractiveElementsHelper.findElementsBySelector(
                    session,
                    selector,
                    { includeCoordinates: true }
                  );
                  return this.formatRuntimeResult(elements2, void 0, "selector");
                }
                console.log("[GetInteractiveElements CDP] Text 查询(3层回退策略)");
                const elements = yield cdpInteractiveElementsHelper.findElements(session, {
                  textQuery,
                  includeCoordinates: true,
                  types: Object.keys(ELEMENT_CONFIG)
                });
                return this.formatRuntimeResult(elements, textQuery, "text-query");
              } catch (error2) {
                console.warn(
                  "[GetInteractiveElements CDP] Runtime.evaluate 失败,回退到快照 API:",
                  error2
                );
                const snapshot = yield this.captureSnapshotInternal(session);
                console.log(
                  "[GetInteractiveElements CDP] 快照包含",
                  snapshot.candidates.length,
                  "个元素"
                );
                let filteredCandidates = snapshot.candidates;
                if (textQuery) {
                  filteredCandidates = this.filterByText(snapshot.candidates, textQuery);
                  console.log(
                    "[GetInteractiveElements CDP] 文本过滤后剩余",
                    filteredCandidates.length,
                    "个元素"
                  );
                }
                return this.formatSnapshotResult(filteredCandidates, snapshot.snapshotId, textQuery);
              }
            })
          );
          return result2;
        } catch (err) {
          console.error("[GetInteractiveElements CDP] 执行失败:", err);
          return error$J(
            `Failed to get interactive elements: ${err instanceof Error ? err.message : String(err)}`,
            "EXECUTION_FAILED",
            { input: args }
          );
        }
      });
    }
    /**
     * 捕获快照（内部版本，直接返回 Candidate 列表，不生成 Markdown）
     */
    captureSnapshotInternal(session) {
      return __async(this, null, function* () {
        var _a3;
        yield session.send("DOM.enable", {});
        yield session.send("CSS.enable", {});
        try {
          try {
            yield session.send("DOM.getDocument", { depth: 0, pierce: true });
          } catch (error2) {
            console.warn("[GetInteractiveElements CDP] DOM 预热失败:", error2);
          }
          const runtimeResult = yield session.send("Runtime.evaluate", {
            expression: "window.devicePixelRatio || 1",
            returnByValue: true
          });
          const devicePixelRatio = ((_a3 = runtimeResult.result) == null ? void 0 : _a3.value) || 1;
          console.log(`[GetInteractiveElements CDP] 设备像素比 (DPR): ${devicePixelRatio}`);
          console.log("[GetInteractiveElements CDP] 开始捕获 DOMSnapshot");
          const snapshot = yield session.send("DOMSnapshot.captureSnapshot", {
            computedStyles: ["display", "visibility", "opacity", "pointer-events"],
            includeDOMRects: true,
            includePaintOrder: true
          });
          console.log("[GetInteractiveElements CDP] 快照获取成功");
          const candidates = extractCandidates(snapshot, devicePixelRatio);
          const sorted = sortCandidates(candidates);
          const snapshotId = String(this.snapshotCounter++);
          sorted.forEach((candidate, i2) => {
            candidate.id = `${snapshotId}_${i2}`;
          });
          console.log(`[GetInteractiveElements CDP] 提取了 ${sorted.length} 个候选元素`);
          return { candidates: sorted, snapshotId };
        } finally {
          yield session.send("CSS.disable", {});
          yield session.send("DOM.disable", {});
        }
      });
    }
    /**
     * 从 Candidate 中提取可搜索文本
     */
    extractSearchableText(candidate) {
      const parts = [];
      const attrs = candidate.attributes;
      if (attrs["aria-label"]) parts.push(attrs["aria-label"]);
      if (attrs.title) parts.push(attrs.title);
      if (attrs.placeholder) parts.push(attrs.placeholder);
      if (attrs.value) parts.push(attrs.value);
      if (attrs.alt) parts.push(attrs.alt);
      if (attrs.href) parts.push(attrs.href);
      return parts.join(" ");
    }
    /**
     * 模糊匹配算法（子序列匹配）
     * 例如："sbmt" 可以匹配 "Submit Button"
     */
    fuzzyMatch(text, query) {
      if (!text || !query) return false;
      const lowerText = text.toLowerCase();
      const lowerQuery = query.toLowerCase();
      let textIndex = 0;
      let queryIndex = 0;
      while (textIndex < lowerText.length && queryIndex < lowerQuery.length) {
        if (lowerText[textIndex] === lowerQuery[queryIndex]) {
          queryIndex++;
        }
        textIndex++;
      }
      return queryIndex === lowerQuery.length;
    }
    /**
     * 按文本查询过滤候选元素
     */
    filterByText(candidates, textQuery) {
      return candidates.filter((candidate) => {
        const searchText = this.extractSearchableText(candidate);
        return this.fuzzyMatch(searchText, textQuery);
      });
    }
    /**
     * 从元素属性中提取可读文本（优先级顺序）
     */
    extractElementText(candidate) {
      const attrs = candidate.attributes;
      const text = attrs["aria-label"] || attrs.title || attrs.placeholder || attrs.value || attrs.alt || attrs.name || "";
      if (!text && attrs.href) {
        try {
          const url2 = new URL(attrs.href, "http://dummy");
          return url2.pathname;
        } catch (e) {
          return attrs.href;
        }
      }
      return text.trim();
    }
    /**
     * 生成元素的简短描述
     */
    generateElementLabel(candidate) {
      const text = this.extractElementText(candidate);
      const tag = candidate.tagName;
      if (text) {
        return `${tag}: ${text}`;
      }
      if (tag === "a") return "Link (no text)";
      if (tag === "button") return "Button (no text)";
      if (tag === "input") {
        const type2 = candidate.attributes.type || "text";
        return `Input [${type2}]`;
      }
      return tag;
    }
    /**
     * 格式化快照结果(DOMSnapshot API)
     */
    formatSnapshotResult(candidates, snapshotId, textQuery) {
      const message = candidates.length === 0 ? textQuery ? `No interactive elements found matching "${textQuery}"` : "No interactive elements found on this page" : void 0;
      return success$1(
        JSON.stringify(
          {
            snapshotId,
            elementCount: candidates.length,
            query: textQuery || null,
            method: "dom-snapshot",
            // 标识使用的方法
            message,
            elements: candidates.map((c) => ({
              // 核心字段（必需）
              uid: c.id,
              label: this.generateElementLabel(c),
              // 可读标签
              text: this.extractElementText(c),
              // 纯文本
              rect: c.rect,
              // 位置坐标
              // 辅助字段（帮助理解）
              tagName: c.tagName,
              // 技术字段（按需使用）
              backendNodeId: c.backendNodeId,
              // 用于 CDP 操作
              paintOrder: c.paintOrder,
              // 层级信息
              // 精简的属性（只保留关键属性）
              attributes: {
                id: c.attributes.id,
                class: c.attributes.class,
                role: c.attributes.role,
                type: c.attributes.type,
                name: c.attributes.name,
                href: c.attributes.href
              }
            }))
          },
          null,
          2
        ),
        { snapshotId, elementCount: candidates.length, method: "dom-snapshot" }
      );
    }
    /**
     * 格式化 Runtime.evaluate 结果
     */
    formatRuntimeResult(elements, textQuery, queryType) {
      const snapshotId = String(this.snapshotCounter++);
      const message = elements.length === 0 ? textQuery ? `No interactive elements found matching "${textQuery}"` : "No interactive elements found on this page" : void 0;
      return success$1(
        JSON.stringify(
          {
            snapshotId,
            elementCount: elements.length,
            query: textQuery || null,
            queryType: queryType || "text-query",
            // 标识查询类型
            method: "runtime-evaluate",
            // 标识使用的方法
            message,
            elements: elements.map((el, i2) => {
              var _a3;
              return {
                // 核心字段
                uid: `${snapshotId}_${i2}`,
                label: `${el.type}: ${el.text}`,
                text: el.text,
                rect: (_a3 = el.coordinates) == null ? void 0 : _a3.rect,
                // 辅助字段
                selector: el.selector,
                tagName: this.extractTagFromSelector(el.selector),
                isInteractive: el.isInteractive,
                disabled: el.disabled,
                // 兼容字段(保留但为 null)
                backendNodeId: null,
                paintOrder: null,
                // 技术字段
                attributes: {
                  href: el.href,
                  checked: el.checked
                }
              };
            })
          },
          null,
          2
        ),
        {
          snapshotId,
          elementCount: elements.length,
          method: "runtime-evaluate",
          queryType: queryType || "text-query"
        }
      );
    }
    /**
     * 从选择器提取标签名
     */
    extractTagFromSelector(selector) {
      const match = selector.match(/^([a-z]+)/);
      return match ? match[1] : "unknown";
    }
    /**
     * 检查 URL 是否受限制
     */
    isRestrictedUrl(url2) {
      if (!url2) return false;
      return url2.startsWith("chrome://") || url2.startsWith("edge://") || url2.startsWith("https://chrome.google.com/webstore") || url2.startsWith("https://microsoftedge.microsoft.com/") || url2.includes("chrome-extension://");
    }
  }
  const getInteractiveElementsToolCDP = new GetInteractiveElementsToolCDP();
  const browserTools = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
    __proto__: null,
    accessibilitySnapshotTool,
    backgroundNetworkRequestTool,
    clickToolCDP,
    closeTabsTool,
    consoleTool,
    executeScriptTool,
    fetchApiBatchTool,
    fetchApiTool,
    fileUploadToolCDP,
    fillToolCDP: fillTool,
    getInteractiveElementsToolCDP,
    getWebContentToolCDP,
    goBackOrForwardTool,
    highlightElementsTool,
    injectScriptTool,
    keyboardToolCDP: keyboardTool,
    navigateToolCDP,
    networkCaptureStartTool,
    networkCaptureStopTool,
    networkDebuggerStartTool,
    networkDebuggerStopTool,
    networkRequestTool,
    pageProtectionDisableTool,
    pageProtectionEnableTool,
    pageProtectionStatusTool,
    removeHighlightsTool,
    screenshotToolCDP: screenshotTool,
    screenshotWithHighlightsTool,
    scrollIntoViewToolCDP: scrollIntoViewTool,
    scrollToolCDP: scrollTool,
    sendCommandToInjectScriptTool,
    waitForElementToolCDP,
    windowTool
  }, Symbol.toStringTag, { value: "Module" }));
  function compose(middlewares) {
    if (!Array.isArray(middlewares)) {
      throw new TypeError("中间件必须是数组");
    }
    for (const middleware of middlewares) {
      if (typeof middleware !== "function") {
        throw new TypeError("中间件必须是函数");
      }
    }
    return function composedMiddleware(context, next) {
      let lastCalledIndex = -1;
      function dispatch(index2) {
        if (index2 <= lastCalledIndex) {
          return Promise.reject(new Error("next() 在同一个中间件中被多次调用"));
        }
        lastCalledIndex = index2;
        if (index2 === middlewares.length) {
          return next();
        }
        const middleware = middlewares[index2];
        try {
          return Promise.resolve(middleware(context, () => dispatch(index2 + 1)));
        } catch (error2) {
          return Promise.reject(error2);
        }
      }
      return dispatch(0);
    };
  }
  function executeWithMiddleware(context, executor, middlewares) {
    return __async(this, null, function* () {
      const coreExecutor = () => __async(null, null, function* () {
        return yield executor.execute(context.args, context);
      });
      const composedMiddleware = compose(middlewares);
      return yield composedMiddleware(context, coreExecutor);
    });
  }
  function createExecutionContext(options) {
    return {
      toolName: options.toolName,
      args: options.args,
      chatId: options.chatId,
      sessionId: options.sessionId,
      isTerminal: options.isTerminal,
      port: options.port,
      metadata: options.metadata || {},
      state: {}
      // 初始化空状态对象
    };
  }
  const errorHandlerMiddleware = (context, next) => __async(null, null, function* () {
    try {
      return yield next();
    } catch (error2) {
      console.error(`[Middleware] Tool ${context.toolName} 执行失败:`, error2);
      return createErrorResponse(
        error2 instanceof Error ? error2.message : ERROR_MESSAGES.TOOL_EXECUTION_FAILED
      );
    }
  });
  class BackgroundExecutionManager {
    constructor() {
      /** 记录已启用保活的 Tab */
      __publicField2(this, "enabledTabIds", /* @__PURE__ */ new Set());
      chrome.tabs.onRemoved.addListener((tabId) => {
        if (this.enabledTabIds.has(tabId)) {
          console.log(`[CDP Background] Tab ${tabId} 已关闭，清理保活状态`);
          this.enabledTabIds.delete(tabId);
        }
      });
    }
    /**
     * 启用后台执行保活（幂等性）
     */
    enableBackgroundExecution(tabId) {
      return __async(this, null, function* () {
        try {
          yield cdpDebuggerManager.attachDebugger(tabId);
          try {
            yield cdpDebuggerManager.sendCommand(tabId, "Emulation.setFocusEmulationEnabled", {
              enabled: true
            });
            console.log(`[CDP Background] ✅ Tab ${tabId} 焦点模拟已启用`);
          } catch (error2) {
            console.warn(`[CDP Background] ⚠️ Tab ${tabId} 焦点模拟失败:`, error2);
          }
          try {
            yield cdpDebuggerManager.sendCommand(tabId, "Runtime.evaluate", {
              expression: `
            (function() {
              if (window.__mcpKeepAliveEnabled) {
                return { success: true, message: 'Already enabled' };
              }

              try {
                // 覆盖 document.hidden
                Object.defineProperty(document, 'hidden', {
                  get: () => false,
                  configurable: true
                });

                // 覆盖 document.visibilityState
                Object.defineProperty(document, 'visibilityState', {
                  get: () => 'visible',
                  configurable: true
                });

                // 覆盖 document.hasFocus()
                document.hasFocus = function() {
                  return true;
                };

                // 拦截 visibilitychange 事件
                const originalAddEventListener = document.addEventListener;
                document.addEventListener = function(type, listener, options) {
                  if (type === 'visibilitychange') {
                    console.log('[MCP Background] 拦截了 visibilitychange 事件监听器');
                    return;
                  }
                  return originalAddEventListener.call(this, type, listener, options);
                };

                window.__mcpKeepAliveEnabled = true;
                console.log('[MCP Background] ✅ 可见性 API 已覆盖');
                return { success: true };
              } catch (error) {
                console.error('[MCP Background] ❌ 覆盖失败:', error);
                return { success: false, error: error.message };
              }
            })()
          `,
              returnByValue: true,
              awaitPromise: false
            });
            console.log(`[CDP Background] ✅ Tab ${tabId} 可见性 API 已覆盖`);
          } catch (error2) {
            console.warn(`[CDP Background] ⚠️ Tab ${tabId} 可见性覆盖失败:`, error2);
          }
          try {
            yield cdpDebuggerManager.sendCommand(tabId, "Emulation.setIdleOverride", {
              isUserActive: true,
              isScreenUnlocked: true
            });
            console.log(`[CDP Background] ✅ Tab ${tabId} 空闲覆盖已启用`);
          } catch (error2) {
            console.warn(`[CDP Background] ⚠️ Tab ${tabId} 空闲覆盖失败:`, error2);
          }
          this.enabledTabIds.add(tabId);
          console.log(`[CDP Background] ✅ Tab ${tabId} 后台执行保活已完成`);
        } catch (error2) {
          console.error(`[CDP Background] ❌ Tab ${tabId} 启用保活失败:`, error2);
        }
      });
    }
  }
  const backgroundExecutionManager = new BackgroundExecutionManager();
  const cdpBackgroundExecutionMiddleware = (context, next) => __async(null, null, function* () {
    var _a3;
    const tabId = context.args.tabId || ((_a3 = context.metadata) == null ? void 0 : _a3.tabId);
    if (tabId) {
      try {
        yield backgroundExecutionManager.enableBackgroundExecution(tabId);
      } catch (error2) {
        console.warn(`[CDP Background] 启用保活失败，降级到前台执行:`, error2);
      }
    }
    return yield next();
  });
  const STORAGE_KEY = "active_sessions_v1";
  const SESSION_EVENTS = {
    SESSIONS_CHANGED: "session:changed",
    SESSION_CREATED: "session:created",
    SESSION_UPDATED: "session:updated",
    SESSION_REMOVED: "session:removed"
  };
  const BACKEND_STATUS_MAP = {
    running: "active",
    waiting_takeover: "waiting_takeover",
    takeover: "takeover",
    completed: "completed",
    failed: "error",
    interrupted: "interrupted",
    // 兜底映射：当本地状态被错误广播为 'active' 时，避免映射到 undefined
    active: "active"
    // 虽然 BackendSessionStatus 类型中没有 'active'，但作为运行时防御
  };
  const FRONTEND_TO_BACKEND_STATUS_MAP = {
    active: "running",
    streaming: "running",
    // streaming 在后端也是 running
    waiting_takeover: "waiting_takeover",
    takeover: "takeover",
    idle: "running",
    // idle 映射到 running（session 存在但无活动）
    completed: "completed",
    interrupted: "interrupted",
    error: "failed"
  };
  const TERMINAL_STATUSES = [
    "completed",
    // ✅ 已完成
    "error",
    // ✅ 错误
    "interrupted"
    // ✅ 中断
  ];
  const types = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
    __proto__: null,
    BACKEND_STATUS_MAP,
    FRONTEND_TO_BACKEND_STATUS_MAP,
    SESSION_EVENTS,
    STORAGE_KEY,
    TERMINAL_STATUSES
  }, Symbol.toStringTag, { value: "Module" }));
  function createDefaultStorageData() {
    return {
      sessions: {},
      version: 1,
      lastUpdated: 0
    };
  }
  function loadSessions() {
    return __async(this, null, function* () {
      try {
        const result2 = yield chrome.storage.local.get(STORAGE_KEY);
        const data = result2[STORAGE_KEY] || createDefaultStorageData();
        const waitDeleteSessionIds = [];
        yield Promise.all(
          Object.values(data.sessions).map((session) => __async(null, null, function* () {
            if (session.tabGroupId) {
              try {
                yield chrome.tabGroups.get(session.tabGroupId);
              } catch (error2) {
                waitDeleteSessionIds.push(session.sessionId);
              }
            }
          }))
        );
        waitDeleteSessionIds.forEach((sessionId) => {
          delete data.sessions[sessionId];
        });
        if (waitDeleteSessionIds.length > 0) {
          yield saveSessions(data);
        }
        return data;
      } catch (error2) {
        console.error("[SessionStorage] Failed to load sessions:", error2);
        return createDefaultStorageData();
      }
    });
  }
  function saveSessions(data) {
    return __async(this, null, function* () {
      try {
        data.lastUpdated = Date.now();
        yield chrome.storage.local.set({ [STORAGE_KEY]: data });
      } catch (error2) {
        console.error("[SessionStorage] Failed to save sessions:", error2);
        throw error2;
      }
    });
  }
  function clearAllSessions() {
    return __async(this, null, function* () {
      yield saveSessions(createDefaultStorageData());
    });
  }
  class SessionManager {
    constructor() {
      __publicField2(this, "listeners", /* @__PURE__ */ new Set());
      __publicField2(this, "broadcastDebounceMap", /* @__PURE__ */ new Map());
      __publicField2(this, "BROADCAST_DEBOUNCE_MS", 300);
    }
    // ============================================================
    // 核心 API
    // ============================================================
    /**
     * 追踪 Session
     * tool 执行时调用，记录 sessionId 到存储
     */
    trackSession(_0) {
      return __async(this, arguments, function* (sessionId, options = {}) {
        const data = yield loadSessions();
        const now = Date.now();
        let session = data.sessions[sessionId];
        const isNew = !session;
        if (isNew) {
          session = {
            sessionId,
            status: "active",
            createdAt: now,
            lastActiveAt: now,
            tabs: [],
            // 设置默认保护级别
            currentToolProtectionLevel: "full",
            currentToolProtectionReason: "默认完全保护"
          };
          const { fetchSessionStatus: fetchSessionStatus2 } = yield Promise.resolve().then(() => sessionApi);
          const response = yield fetchSessionStatus2(sessionId);
          if (response && response.success && response.data) {
            const backendStatus = response.data;
            const localStatus = BACKEND_STATUS_MAP[backendStatus.status] || "idle";
            session.status = localStatus;
            session.title = backendStatus.title;
          }
          console.log(`[SessionManager] Created new session: ${sessionId}`);
        } else {
          session.lastActiveAt = now;
        }
        if (options.toolName) {
          session.currentToolName = options.toolName;
          console.log(`[SessionManager] Tool ${options.toolName} 开始执行`);
        }
        if (options.windowId !== void 0) {
          session.windowId = options.windowId;
        }
        data.sessions[sessionId] = session;
        yield saveSessions(data);
        yield this.notifyChange();
        this.broadcast(
          isNew ? SESSION_EVENTS.SESSION_CREATED : SESSION_EVENTS.SESSION_UPDATED,
          session
        );
        return session;
      });
    }
    /**
     * 更新 Session 状态
     * 由轮询逻辑调用，根据后端返回更新本地状态
     */
    updateStatus(sessionId, status, backendStatus) {
      return __async(this, null, function* () {
        const data = yield loadSessions();
        const session = data.sessions[sessionId];
        if (!session) {
          console.warn(`[SessionManager] Session not found: ${sessionId}`);
          return;
        }
        session.status = status;
        session.lastActiveAt = Date.now();
        yield saveSessions(data);
        yield this.notifyChange();
        this.broadcast(SESSION_EVENTS.SESSION_UPDATED, {
          session,
          backendStatus,
          // ✅ 携带后端状态
          trigger: "user_action",
          timestamp: Date.now()
        });
      });
    }
    /**
     * 开始接管 Session
     * 用户点击接管按钮时调用
     */
    startTakeover(sessionId) {
      return __async(this, null, function* () {
        console.log(`[SessionManager] Starting takeover for session: ${sessionId}`);
        yield this.updateStatus(sessionId, "takeover");
      });
    }
    /**
     * 结束接管，恢复为 active 状态
     * 用户提交接管信息后调用
     */
    endTakeover(sessionId) {
      return __async(this, null, function* () {
        console.log(`[SessionManager] Ending takeover for session: ${sessionId}`);
        try {
          const { fetchSessionStatus: fetchSessionStatus2 } = yield Promise.resolve().then(() => sessionApi);
          const response = yield fetchSessionStatus2(sessionId);
          if (response && response.success && response.data) {
            const backendStatus = response.data;
            const localStatus = BACKEND_STATUS_MAP[backendStatus.status] || "idle";
            console.log(
              `[SessionManager] 查询到后端状态: ${backendStatus.status} → 本地状态: ${localStatus}`
            );
            yield this.updateStatus(sessionId, localStatus, backendStatus);
          } else {
            console.warn("[SessionManager] 查询后端状态失败，回退到 active 状态");
            yield this.updateStatus(sessionId, "active", {
              status: "running",
              // active 对应后端的 running
              title: "",
              sessionId
            });
          }
        } catch (error2) {
          console.error(`[SessionManager] 查询后端状态异常:`, error2);
          yield this.updateStatus(sessionId, "active", {
            status: "running",
            title: "",
            sessionId
          });
        }
      });
    }
    // ============================================================
    // Tab Group 管理
    // ============================================================
    /**
     * 设置 session 的 tab group ID
     */
    setTabGroupId(sessionId, groupId, windowId) {
      return __async(this, null, function* () {
        const data = yield loadSessions();
        const session = data.sessions[sessionId];
        if (!session) return;
        session.tabGroupId = groupId;
        session.windowId = windowId;
        yield saveSessions(data);
        yield this.notifyChange();
        console.log(`[SessionManager] Set tabGroupId ${groupId} for session ${sessionId}`);
        this.fetchAndUpdateTabGroupTitle(sessionId, groupId);
      });
    }
    /**
     * 立即从后端获取 session 信息并更新 Tab Group title
     * 异步执行，不阻塞主流程
     */
    fetchAndUpdateTabGroupTitle(sessionId, groupId) {
      return __async(this, null, function* () {
        try {
          const { fetchSessionStatus: fetchSessionStatus2 } = yield Promise.resolve().then(() => sessionApi);
          const data = yield fetchSessionStatus2(sessionId);
          const backendStatus = data == null ? void 0 : data.data;
          if (backendStatus == null ? void 0 : backendStatus.title) {
            yield chrome.tabGroups.update(groupId, {
              title: backendStatus.title
            });
            console.log(`[SessionManager] Immediately updated tabGroup title: ${backendStatus.title}`);
            const data2 = yield loadSessions();
            const session = data2.sessions[sessionId];
            if (session) {
              session.title = backendStatus.title;
              yield saveSessions(data2);
            }
          }
        } catch (error2) {
          console.warn(`[SessionManager] Failed to fetch and update tabGroup title:`, error2);
        }
      });
    }
    /**
     * 添加 tab 到 session 的 tabs 数组
     */
    addTabToSession(sessionId, tab) {
      return __async(this, null, function* () {
        const data = yield loadSessions();
        const session = data.sessions[sessionId];
        if (!session) return;
        const existingIndex = session.tabs.findIndex((t) => t.tabId === tab.tabId);
        if (existingIndex >= 0) {
          session.tabs[existingIndex].lastAccessedAt = tab.lastAccessedAt;
          session.tabs[existingIndex].url = tab.url;
          session.tabs[existingIndex].title = tab.title;
        } else {
          session.tabs.push(tab);
        }
        yield saveSessions(data);
      });
    }
    // ============================================================
    // 查询
    // ============================================================
    /**
     * 获取所有活跃 sessions
     */
    getActiveSessions() {
      return __async(this, null, function* () {
        const data = yield loadSessions();
        return Object.values(data.sessions).filter(
          (s) => s.status === "active" || s.status === "streaming"
        );
      });
    }
    /**
     * 获取所有 sessions
     */
    getAllSessions() {
      return __async(this, null, function* () {
        const data = yield loadSessions();
        return Object.values(data.sessions);
      });
    }
    /**
     * 获取单个 session
     */
    getSession(sessionId) {
      return __async(this, null, function* () {
        const data = yield loadSessions();
        return data.sessions[sessionId] || null;
      });
    }
    /**
     * 根据 tabId 查找关联的 sessionId
     * 遍历所有 session 的 tabs 数组，查找包含指定 tabId 的 session
     */
    getSessionByTabId(tabId) {
      return __async(this, null, function* () {
        const data = yield loadSessions();
        for (const session of Object.values(data.sessions)) {
          const hasTab = session.tabs.some((t) => String(t.tabId) === String(tabId));
          if (hasTab) {
            return session;
          }
        }
        return null;
      });
    }
    /**
     * 根据 Tab Group ID 查找关联的 sessionId
     * 遍历所有 session，查找包含指定 tabGroupId 的 session
     */
    getSessionByGroupId(groupId) {
      return __async(this, null, function* () {
        const data = yield loadSessions();
        for (const session of Object.values(data.sessions)) {
          if (session.tabGroupId === groupId) {
            return session;
          }
        }
        return null;
      });
    }
    /**
     * 通过 Tab Group ID 查找对应的 Session
     * 用于 tab 事件监听器快速定位 session
     * （getSessionByGroupId 的别名，用于事件处理场景）
     */
    findSessionByTabGroupId(groupId) {
      return __async(this, null, function* () {
        return this.getSessionByGroupId(groupId);
      });
    }
    /**
     * 通过 Tab ID 查找对应的 Session
     * 用于处理 tab 已移出 group 的情况
     * （getSessionByTabId 的别名，用于事件处理场景）
     */
    findSessionByTabId(tabId) {
      return __async(this, null, function* () {
        return this.getSessionByTabId(tabId);
      });
    }
    // ============================================================
    // 清理
    // ============================================================
    /**
     * 根据 Tab Group ID 删除 session
     */
    removeSessionByGroupId(groupId) {
      return __async(this, null, function* () {
        const data = yield loadSessions();
        let removed = false;
        for (const [sessionId, session] of Object.entries(data.sessions)) {
          if (session.tabGroupId === groupId) {
            delete data.sessions[sessionId];
            console.log(`[SessionManager] Removed session by groupId: ${sessionId}`);
            removed = true;
            this.broadcast(SESSION_EVENTS.SESSION_REMOVED, { sessionId });
          }
        }
        if (removed) {
          yield saveSessions(data);
          yield this.notifyChange();
        }
      });
    }
    /**
     * 根据窗口 ID 删除所有 sessions
     */
    removeSessionsByWindowId(windowId) {
      return __async(this, null, function* () {
        const data = yield loadSessions();
        let removed = false;
        for (const [sessionId, session] of Object.entries(data.sessions)) {
          if (session.windowId === windowId) {
            delete data.sessions[sessionId];
            console.log(`[SessionManager] Removed session by windowId: ${sessionId}`);
            removed = true;
            this.broadcast(SESSION_EVENTS.SESSION_REMOVED, { sessionId });
          }
        }
        if (removed) {
          yield saveSessions(data);
          yield this.notifyChange();
        }
      });
    }
    /**
     * 清空所有 sessions
     */
    clearAllSessions() {
      return __async(this, null, function* () {
        console.log("[SessionManager] Clearing all sessions");
        yield clearAllSessions();
        yield this.notifyChange();
        this.broadcast(SESSION_EVENTS.SESSIONS_CHANGED, []);
      });
    }
    // ============================================================
    // 辅助方法
    // ============================================================
    /**
     * 判断是否为终态状态（无需继续同步）
     */
    isTerminalStatus(status) {
      return TERMINAL_STATUSES.includes(status);
    }
    /**
     * 从后端 API 响应更新 Session
     * @deprecated 使用 updateFromApiWithTimestamp 代替
     */
    updateFromApi(sessionId, backendStatus) {
      return __async(this, null, function* () {
        yield this.updateFromApiWithTimestamp(sessionId, backendStatus, Date.now());
      });
    }
    /**
     * 从 API 响应更新 session 状态（带时间戳）
     * @param sessionId Session ID
     * @param backendStatus 后端返回的 status 数据
     * @param apiTimestamp API 响应的时间戳（毫秒）
     */
    updateFromApiWithTimestamp(sessionId, backendStatus, apiTimestamp) {
      return __async(this, null, function* () {
        const { BACKEND_STATUS_MAP: BACKEND_STATUS_MAP2 } = yield Promise.resolve().then(() => types);
        const data = yield loadSessions();
        const session = data.sessions[sessionId];
        if (!session) {
          console.warn(`[SessionManager] Session ${sessionId} 不存在`);
          return;
        }
        const lastTimestamp = session.lastPushTimestamp || 0;
        if (apiTimestamp <= lastTimestamp) {
          console.log(`[SessionManager] API 数据过期 (${apiTimestamp} <= ${lastTimestamp})，跳过`);
          return;
        }
        const newStatus = BACKEND_STATUS_MAP2[backendStatus.status];
        if (!newStatus) {
          console.warn(`[SessionManager] Unknown backend status: ${backendStatus.status}`);
          return;
        }
        const oldStatus = session.status;
        if (oldStatus !== newStatus) {
          console.log(`[SessionManager] API 同步状态: ${oldStatus} → ${newStatus}`);
          session.status = newStatus;
          session.title = backendStatus.title;
          session.lastPushTimestamp = apiTimestamp;
          session.lastActiveAt = Date.now();
          yield saveSessions(data);
          yield this.notifyChange();
          if (session.tabGroupId && backendStatus.title) {
            try {
              yield chrome.tabGroups.update(session.tabGroupId, {
                title: backendStatus.title
              });
            } catch (error2) {
              console.warn("[SessionManager] 更新 Tab Group 标题失败:", error2);
            }
          }
          this.debouncedBroadcast(
            SESSION_EVENTS.SESSION_UPDATED,
            {
              session,
              backendStatus,
              trigger: "api_poll",
              timestamp: Date.now()
            },
            sessionId
          );
        } else {
          session.lastPushTimestamp = apiTimestamp;
          yield saveSessions(data);
        }
      });
    }
    // ============================================================
    // WebSocket 推送处理
    // ============================================================
    /**
     * 处理 WebSocket 推送的状态变更
     * @param sessionId Session ID
     * @param oldBackendStatus 后端的旧状态（用于 CAS 验证）
     * @param newBackendStatus 后端的新状态
     * @param pushTimestamp 推送消息的时间戳（用于去重）
     */
    handleStatusPush(sessionId, oldBackendStatus, newBackendStatus, pushTimestamp) {
      return __async(this, null, function* () {
        const { BACKEND_STATUS_MAP: BACKEND_STATUS_MAP2 } = yield Promise.resolve().then(() => types);
        console.log(
          `[SessionManager] 收到推送: sessionId=${sessionId}, ${oldBackendStatus} → ${newBackendStatus}, ts=${pushTimestamp}`
        );
        const data = yield loadSessions();
        const session = data.sessions[sessionId];
        if (!session) {
          console.warn(`[SessionManager] Session ${sessionId} 不存在，忽略推送`);
          return;
        }
        const lastUpdateTimestamp = session.lastPushTimestamp || 0;
        if (pushTimestamp <= lastUpdateTimestamp) {
          console.log(
            `[SessionManager] 推送消息过期 (${pushTimestamp} <= ${lastUpdateTimestamp})，忽略`
          );
          return;
        }
        const currentFrontendStatus = session.status;
        const currentBackendStatus = FRONTEND_TO_BACKEND_STATUS_MAP[currentFrontendStatus];
        if (currentBackendStatus !== oldBackendStatus) {
          console.warn(
            `[SessionManager] 后端状态不同步！本地后端状态=${currentBackendStatus}, 推送旧状态=${oldBackendStatus}`
          );
          console.warn("[SessionManager] 可能漏掉了中间状态，主动查询最新状态...");
          const { fetchSessionStatus: fetchSessionStatus2 } = yield Promise.resolve().then(() => sessionApi);
          const response = yield fetchSessionStatus2(sessionId);
          if (response && response.success) {
            const apiTimestamp = new Date(response.timestamp).getTime();
            yield this.updateFromApiWithTimestamp(sessionId, response.data, apiTimestamp);
          } else {
            console.error("[SessionManager] 查询最新状态失败");
          }
          return;
        }
        const newFrontendStatus = BACKEND_STATUS_MAP2[newBackendStatus] || "idle";
        if (currentFrontendStatus === newFrontendStatus) {
          console.log(`[SessionManager] 状态未变化 (${currentFrontendStatus})，跳过更新`);
          session.lastPushTimestamp = pushTimestamp;
          yield saveSessions(data);
          return;
        }
        console.log(`[SessionManager] 状态变更: ${currentFrontendStatus} → ${newFrontendStatus}`);
        session.status = newFrontendStatus;
        session.lastPushTimestamp = pushTimestamp;
        session.lastActiveAt = Date.now();
        yield saveSessions(data);
        yield this.notifyChange();
        const backendStatus = {
          sessionId,
          status: newBackendStatus,
          title: session.title || "",
          createdAt: new Date(session.createdAt).toISOString()
        };
        if ((session == null ? void 0 : session.tabGroupId) && !(session == null ? void 0 : session.title)) {
          try {
            yield this.fetchAndUpdateTabGroupTitle(sessionId, session.tabGroupId);
          } catch (error2) {
            console.warn("[SessionManager] 更新 Tab Group 标题失败:", error2);
          }
        }
        this.debouncedBroadcast(
          SESSION_EVENTS.SESSION_UPDATED,
          {
            session,
            backendStatus,
            trigger: "websocket_push",
            // ✅ 新增 trigger 类型
            timestamp: Date.now()
          },
          sessionId
        );
      });
    }
    /**
     * WebSocket 连接/重连成功时的回调
     * ✅ 立即同步所有活跃 sessions 的最新状态，防止断线期间漏掉的变更
     */
    onWebSocketConnected() {
      console.log("[SessionManager] WebSocket 已连接，同步所有活跃 sessions...");
      this.syncAllSessionsOnConnect();
    }
    /**
     * 同步所有活跃 sessions 的最新状态
     * ✅ 防止在断线期间漏掉的状态变更
     */
    syncAllSessionsOnConnect() {
      return __async(this, null, function* () {
        const sessions = yield this.getAllSessions();
        const activeSessions = sessions.filter((s) => !this.isTerminalStatus(s.status));
        if (activeSessions.length === 0) {
          console.log("[SessionManager] 没有活跃 sessions，跳过同步");
          return;
        }
        const sessionIds = activeSessions.map((s) => s.sessionId);
        const { fetchSessionStatuses: fetchSessionStatuses2 } = yield Promise.resolve().then(() => sessionApi);
        const responses = yield fetchSessionStatuses2(sessionIds);
        for (const [sessionId, responseData] of responses) {
          const apiTimestamp = responseData.timestamp ? new Date(responseData.timestamp).getTime() : Date.now();
          yield this.updateFromApiWithTimestamp(sessionId, responseData.data, apiTimestamp);
        }
        console.log(`[SessionManager] 已同步 ${responses.size} 个 sessions 的最新状态`);
      });
    }
    /**
     * 判断 session 是否为终态状态
     */
    isTerminalSession(sessionId) {
      return __async(this, null, function* () {
        const session = yield this.getSession(sessionId);
        return session ? this.isTerminalStatus(session.status) : false;
      });
    }
    // ============================================================
    // 订阅与通知
    // ============================================================
    subscribe(callback) {
      this.listeners.add(callback);
      return () => this.listeners.delete(callback);
    }
    notifyChange() {
      return __async(this, null, function* () {
        const sessions = yield this.getAllSessions();
        this.listeners.forEach((cb) => {
          try {
            cb(sessions);
          } catch (error2) {
            console.error("[SessionManager] Listener error:", error2);
          }
        });
      });
    }
    debouncedBroadcast(event, payload, sessionId) {
      const key = sessionId || "global";
      const existing = this.broadcastDebounceMap.get(key);
      if (existing) clearTimeout(existing);
      const timer = setTimeout(() => {
        this.broadcast(event, payload);
        this.broadcastDebounceMap.delete(key);
      }, this.BROADCAST_DEBOUNCE_MS);
      this.broadcastDebounceMap.set(key, timer);
    }
    broadcast(event, payload) {
      chrome.runtime.sendMessage({ type: event, payload }).catch(() => {
      });
    }
  }
  let instance$1 = null;
  function getSessionManager() {
    if (!instance$1) {
      instance$1 = new SessionManager();
    }
    return instance$1;
  }
  class ProtectionController {
    constructor() {
      __publicField2(this, "initialized", false);
    }
    init() {
      if (this.initialized) return;
      this.initialized = true;
      getSessionManager().subscribe((sessions) => __async(this, null, function* () {
        console.log(`[ProtectionController] Syncing ${sessions.length} sessions`);
        for (const session of sessions) {
          if (this.shouldProtect(session.status)) {
            yield this.syncProtectionForSession(session);
          } else {
            for (const tab of session.tabs) {
              yield this.setTabProtection(tab.tabId, { mode: "disabled", takeover: false });
            }
          }
        }
      }));
      getSessionManager().getAllSessions().then((sessions) => {
        console.log(`[ProtectionController] Initial sync for ${sessions.length} sessions`);
        for (const session of sessions) {
          if (this.shouldProtect(session.status)) {
            this.syncProtectionForSession(session);
          }
        }
      });
      console.log("[ProtectionController] Initialized");
    }
    /**
     * 根据 Session 状态计算需要执行的保护动作
     *
     * 设计原则：
     * - Session 级别只根据 status 决定是否启用保护
     * - 进行中的 session 始终 full 保护
     * - 工具执行期间的保护模式切换由 pageProtectionMiddleware 负责
     */
    getProtectionAction(session) {
      const { status } = session;
      if (status === "takeover") {
        return { mode: "full", takeover: true };
      }
      if (status === "waiting_takeover") {
        return { mode: "full", takeover: false };
      }
      if (status !== "active" && status !== "streaming") {
        return { mode: "disabled", takeover: false };
      }
      return { mode: "full", takeover: false };
    }
    /**
     * 判断 Session 是否需要保护（包括接管状态）
     */
    shouldProtect(status) {
      return status === "active" || status === "streaming" || status === "takeover" || status === "waiting_takeover";
    }
    /**
     * Session 状态变化时同步所有 Tab 的保护状态
     */
    syncProtectionForSession(session) {
      return __async(this, null, function* () {
        const action = this.getProtectionAction(session);
        console.log(
          `[ProtectionController] Syncing protection for session ${session.sessionId}: status=${session.status}, protectionLevel=${session.currentToolProtectionLevel}, tabs=${session.tabs.length}`
        );
        for (const tab of session.tabs) {
          yield this.setTabProtection(tab.tabId, action);
        }
      });
    }
    /**
     * 新 Tab 加入 Session 时立即设置保护
     */
    protectNewTab(tabId, session) {
      return __async(this, null, function* () {
        if (this.shouldProtect(session.status)) {
          const action = this.getProtectionAction(session);
          yield this.setTabProtection(tabId, action);
          console.log(
            `[ProtectionController] Protected new tab ${tabId} for session ${session.sessionId}`
          );
        }
      });
    }
    setTabProtection(tabId, action) {
      return __async(this, null, function* () {
        var _a3, _b2;
        try {
          let tab;
          try {
            tab = yield chrome.tabs.get(tabId);
          } catch (e) {
            return;
          }
          if (((_a3 = tab.url) == null ? void 0 : _a3.startsWith("chrome://")) || ((_b2 = tab.url) == null ? void 0 : _b2.startsWith("chrome-extension://"))) {
            return;
          }
          yield chrome.scripting.executeScript({
            target: { tabId },
            files: ["page-protection-helper-v2.js"]
          });
          yield new Promise((resolve2) => setTimeout(resolve2, 200));
          const sendMessageWithRetry = (message, maxRetries = 3) => __async(null, null, function* () {
            for (let i2 = 0; i2 < maxRetries; i2++) {
              try {
                yield chrome.tabs.sendMessage(tabId, message);
                return true;
              } catch (error2) {
                if (i2 === maxRetries - 1) throw error2;
                yield new Promise((resolve2) => setTimeout(resolve2, 100 * (i2 + 1)));
              }
            }
            return false;
          });
          if (action.takeover) {
            yield sendMessageWithRetry({
              action: "START_TAKEOVER"
            });
            console.log(`[ProtectionController] Tab ${tabId} entered takeover mode`);
          } else if ("waitingTakeover" in action && action.waitingTakeover) {
            yield sendMessageWithRetry({
              action: "WAITING_TAKEOVER"
            });
            console.log(`[ProtectionController] Tab ${tabId} entered waiting_takeover mode`);
          } else {
            yield sendMessageWithRetry({
              action: "SET_PROTECTION_MODE",
              mode: action.mode
            });
            console.log(`[ProtectionController] Tab ${tabId} protection set to ${action.mode}`);
          }
        } catch (error2) {
          console.warn(`[ProtectionController] Failed to set protection for tab ${tabId}:`, error2);
        }
      });
    }
  }
  let instance = null;
  function getProtectionController() {
    if (!instance) {
      instance = new ProtectionController();
    }
    return instance;
  }
  function calculateOptimalGroupPosition(windowId) {
    return __async(this, null, function* () {
      try {
        const allTabs = yield chrome.tabs.query({ windowId });
        const pinnedTabs = allTabs.filter((t) => t.pinned);
        const targetIndex = pinnedTabs.length > 0 ? Math.max(...pinnedTabs.map((t) => t.index)) + 1 : 0;
        console.log("[TabGroup] 位置计算:", {
          windowId,
          pinnedCount: pinnedTabs.length,
          targetIndex,
          totalTabs: allTabs.length
        });
        return targetIndex;
      } catch (error2) {
        console.error("[TabGroup] 计算位置失败:", error2);
        return 0;
      }
    });
  }
  function ensureTabInSessionGroup(sessionId, tabId) {
    return __async(this, null, function* () {
      try {
        const session = yield getSessionManager().getSession(sessionId);
        if (!session) {
          console.warn("[TabGroup] Session not found:", sessionId);
          return;
        }
        let tab;
        try {
          tab = yield chrome.tabs.get(tabId);
        } catch (e) {
          console.warn("[TabGroup] Tab not found:", tabId);
          return;
        }
        if (!tab.windowId) {
          console.warn("[TabGroup] Tab has no windowId:", tabId);
          return;
        }
        if (session.tabGroupId && tab.groupId === session.tabGroupId) {
          yield updateTabRecord(sessionId, tab);
          return;
        }
        if (!session.tabGroupId) {
          console.log("[TabGroup] Creating new group for session:", sessionId);
          const targetIndex = yield calculateOptimalGroupPosition(tab.windowId);
          yield chrome.tabs.move(tabId, { index: targetIndex });
          console.log(`[TabGroup] Moved tab ${tabId} to index ${targetIndex}`);
          const groupId = yield chrome.tabs.group({
            tabIds: [tabId],
            createProperties: { windowId: tab.windowId }
          });
          yield chrome.tabGroups.update(groupId, {
            title: "Datasaver",
            color: "blue"
          });
          yield getSessionManager().setTabGroupId(sessionId, groupId, tab.windowId);
        } else {
          console.log("[TabGroup] Adding tab to existing group:", session.tabGroupId);
          try {
            yield chrome.tabs.group({
              tabIds: [tabId],
              groupId: session.tabGroupId
            });
          } catch (e) {
            console.warn("[TabGroup] Failed to add tab to group:", e);
            return;
          }
        }
        yield updateTabRecord(sessionId, tab);
        const protectionController = getProtectionController();
        yield protectionController.protectNewTab(tabId, session);
      } catch (error2) {
        console.error("[TabGroup] Error in ensureTabInSessionGroup:", error2);
      }
    });
  }
  function updateTabRecord(sessionId, tab) {
    return __async(this, null, function* () {
      if (!tab.id) return;
      const tabRecord = {
        tabId: tab.id,
        url: tab.url || "",
        title: tab.title,
        createdAt: Date.now(),
        lastAccessedAt: Date.now()
      };
      yield getSessionManager().addTabToSession(sessionId, tabRecord);
    });
  }
  const TAB_CREATING_TOOLS = ["chrome_navigate"];
  const tabGroupMiddleware = (context, next) => __async(null, null, function* () {
    var _a3;
    const { sessionId, metadata: metadata2, toolName } = context;
    const tabId = metadata2 == null ? void 0 : metadata2.tabId;
    if (!sessionId || !tabId) {
      return next();
    }
    if (TAB_CREATING_TOOLS.includes(toolName)) {
      console.log(`[TabGroup] 跳过创建工具的metadata.tabId: ${toolName}, tabId: ${tabId}`);
      return next();
    }
    try {
      const { getToolMetadata: getToolMetadata2 } = yield Promise.resolve().then(() => index$3);
      const tool = getToolMetadata2(toolName);
      if (((_a3 = tool == null ? void 0 : tool.annotations) == null ? void 0 : _a3.readOnlyHint) === true) {
        console.log(`[TabGroup] 跳过只读工具: ${toolName}, tabId: ${tabId}`);
        return next();
      }
    } catch (error2) {
      console.warn(`[TabGroup] 获取工具元数据失败:`, error2);
    }
    console.log(`[TabGroup] 加入session group: ${toolName}, tabId: ${tabId}`);
    yield ensureTabInSessionGroup(sessionId, tabId);
    return next();
  });
  const TOOL_PROTECTION_MAP = {
    // 只读工具 - blocking 级别
    chrome_screenshot: { level: "blocking", reason: "只读截图" },
    chrome_accessibility_snapshot: { level: "blocking", reason: "只读可访问性快照" },
    chrome_get_web_content: { level: "blocking", reason: "只读页面内容获取" },
    chrome_get_interactive_elements: { level: "blocking", reason: "只读交互元素分析" },
    chrome_wait_for_element: { level: "blocking", reason: "只读元素等待" },
    chrome_highlight_elements: { level: "blocking", reason: "高亮显示需要视觉提示" },
    chrome_remove_highlights: { level: "blocking", reason: "移除高亮需要视觉提示" },
    chrome_screenshot_with_highlights: { level: "blocking", reason: "只读高亮截图" },
    // 交互工具 - visual-only 级别
    chrome_click_element: { level: "visual-only", reason: "防止用户干扰点击操作" },
    chrome_navigate: { level: "visual-only", reason: "页面跳转需要视觉提示" },
    chrome_scroll: { level: "visual-only", reason: "滚动操作需要视觉提示" },
    chrome_scroll_into_view: { level: "visual-only", reason: "滚动定位需要视觉提示" },
    chrome_go_back_or_forward: { level: "visual-only", reason: "后退/前进导航需要视觉提示" },
    chrome_fill_or_select: { level: "visual-only", reason: "防止用户干扰输入操作" },
    chrome_keyboard: { level: "visual-only", reason: "防止用户干扰键盘输入" },
    chrome_input_upload_file: { level: "visual-only", reason: "防止用户干扰文件上传" },
    chrome_close_tabs: { level: "visual-only", reason: "关闭标签需要视觉提示" }
  };
  function getToolProtectionLevel(toolName) {
    return TOOL_PROTECTION_MAP[toolName] || {
      level: "full",
      reason: "未配置的工具默认使用完全保护"
    };
  }
  function sendMessageToTab$1(tabId, message) {
    return __async(this, null, function* () {
      var _a3, _b2, _c2, _d2;
      try {
        const tab = yield chrome.tabs.get(tabId);
        if (((_a3 = tab.url) == null ? void 0 : _a3.startsWith("chrome://")) || ((_b2 = tab.url) == null ? void 0 : _b2.startsWith("chrome-extension://")) || ((_c2 = tab.url) == null ? void 0 : _c2.startsWith("about:"))) {
          return {
            success: false,
            error: "System page - skip protection"
          };
        }
        try {
          const response2 = yield Promise.race([
            chrome.tabs.sendMessage(tabId, message),
            new Promise((_, reject) => setTimeout(() => reject(new Error("Message timeout")), 300))
          ]);
          return { success: true, data: response2 };
        } catch (error2) {
          if (!((_d2 = error2.message) == null ? void 0 : _d2.includes("Could not establish connection"))) {
            throw error2;
          }
          console.log(`[PageProtection] 接收端不存在，准备重新注入脚本 (Tab ${tabId})`);
        }
        try {
          yield chrome.scripting.executeScript({
            target: { tabId },
            files: ["page-protection-helper-v2.js"]
          });
          yield new Promise((resolve2) => setTimeout(resolve2, 50));
        } catch (injectError) {
          console.error(`[PageProtection] 降级注入失败 (Tab ${tabId}):`, injectError);
          throw injectError;
        }
        const response = yield Promise.race([
          chrome.tabs.sendMessage(tabId, message),
          new Promise(
            (_, reject) => setTimeout(() => reject(new Error("Message timeout after retry")), 1e3)
          )
        ]);
        return { success: true, data: response };
      } catch (error2) {
        console.error(`[PageProtection] 发送消息整体失败 (Tab ${tabId}):`, error2);
        return {
          success: false,
          error: error2 instanceof Error ? error2.message : "Unknown error"
        };
      }
    });
  }
  const pageProtectionMiddleware = (context, next) => __async(null, null, function* () {
    var _a3;
    const tabId = context.args.tabId || ((_a3 = context.metadata) == null ? void 0 : _a3.tabId);
    const protectionConfig = getToolProtectionLevel(context.toolName);
    if (!tabId || context.isTerminal) {
      console.log(
        `[PageProtection] 跳过保护管理 (tool=${context.toolName}, tabId=none || isTerminal=true)`
      );
      return yield next();
    }
    let targetMode;
    switch (protectionConfig.level) {
      case "none":
        targetMode = "disabled";
        break;
      case "blocking":
        targetMode = "blocking";
        break;
      case "visual-only":
        targetMode = "visual";
        break;
      case "full":
      default:
        targetMode = "full";
        break;
    }
    let modeChanged = false;
    if (targetMode !== "full") {
      const switchResult = yield sendMessageToTab$1(tabId, {
        action: "SET_PROTECTION_MODE",
        mode: targetMode,
        locked: true
        // 【新增】锁定保护模式，忽略后续同步
      });
      if (switchResult.success) {
        modeChanged = true;
        console.log(
          `[PageProtection] 切换保护模式 full -> ${targetMode} (锁定) (Tab ${tabId}, tool=${context.toolName})`
        );
      } else {
        console.warn(`[PageProtection] 切换保护模式失败 (Tab ${tabId}):`, switchResult.error);
      }
    } else {
      console.log(`[PageProtection] 保持 full 保护 (Tab ${tabId}, tool=${context.toolName})`);
    }
    try {
      return yield next();
    } finally {
      if (modeChanged) {
        const restoreResult = yield sendMessageToTab$1(tabId, {
          action: "SET_PROTECTION_MODE",
          mode: "full",
          unlock: true
          // 【新增】解锁保护模式，允许后续同步
        });
        if (restoreResult.success) {
          console.log(`[PageProtection] 恢复保护模式 ${targetMode} -> full (解锁) (Tab ${tabId})`);
        } else {
          console.warn(
            `[PageProtection] 恢复保护模式失败 (Tab ${tabId}):`,
            restoreResult.error,
            "(Session 级别会在下次同步时恢复)"
          );
        }
      }
    }
  });
  function getActiveTabId() {
    return __async(this, null, function* () {
      try {
        const tabs = yield chrome.tabs.query({ active: true, currentWindow: true });
        if (tabs.length > 0 && tabs[0].id) {
          return tabs[0].id;
        }
        return null;
      } catch (error2) {
        console.warn("[ContextEnrichment] 获取活跃 tab 失败:", error2);
        return null;
      }
    });
  }
  function formatContextForLLM(context) {
    return JSON.stringify(context, null, 2);
  }
  const contextEnrichmentMiddleware = (context, next) => __async(null, null, function* () {
    var _a3, _b2, _c2;
    const result2 = yield next();
    if (result2.isError) {
      return result2;
    }
    try {
      let tabId = context.args.tabId;
      if (!tabId && ((_a3 = result2._meta) == null ? void 0 : _a3.tabId)) {
        tabId = result2._meta.tabId;
      }
      if (!tabId && ((_c2 = (_b2 = result2.content) == null ? void 0 : _b2[0]) == null ? void 0 : _c2.type) === "text") {
        try {
          const resultData = JSON.parse(result2.content[0].text);
          tabId = resultData.tabId;
        } catch (e) {
        }
      }
      if (!tabId) {
        tabId = yield getActiveTabId();
      }
      if (!tabId) {
        return result2;
      }
      let relatedTabsInfo = null;
      if (context.sessionId) {
        try {
          const sessionManager = getSessionManager();
          const session = yield sessionManager.getSession(context.sessionId);
          if (session && session.tabs.length > 0) {
            const scope2 = session.tabGroupId ? "group" : "window";
            const scopeId = session.tabGroupId || session.windowId;
            const sortedTabs = [...session.tabs].sort((a, b) => b.tabId - a.tabId);
            relatedTabsInfo = {
              scope: scope2,
              scopeId,
              scopeName: session.title || "",
              totalTabs: sortedTabs.length,
              tabs: sortedTabs.map((t) => ({
                tabId: t.tabId,
                url: t.url,
                title: t.title || "",
                active: false,
                // session.tabs 中没有 active 字段，默认 false
                index: 0
                // session.tabs 中没有 index 字段，默认 0
              }))
            };
            if (scope2 === "group") {
              try {
                const tabGroup = yield chrome.tabGroups.get(scopeId);
                relatedTabsInfo.color = tabGroup.color;
              } catch (e) {
              }
            }
            console.log(
              `[ContextEnrichment] 从 Session Storage 获取 relatedTabs, scope: ${scope2}, totalTabs: ${sortedTabs.length}`
            );
          }
        } catch (error2) {
          console.warn("[ContextEnrichment] 从 Session Storage 获取失败:", error2);
        }
      }
      if (!relatedTabsInfo) {
        let tab;
        try {
          tab = yield chrome.tabs.get(tabId);
        } catch (error2) {
          console.warn(`[ContextEnrichment] Tab ${tabId} 无法访问:`, error2);
          return result2;
        }
        if (tab.groupId !== void 0 && tab.groupId !== chrome.tabGroups.TAB_GROUP_ID_NONE) {
          try {
            const tabGroup = yield chrome.tabGroups.get(tab.groupId);
            const allGroupTabs = yield chrome.tabs.query({ groupId: tab.groupId });
            const sortedTabs = allGroupTabs.sort((a, b) => (b.id || 0) - (a.id || 0));
            relatedTabsInfo = {
              scope: "group",
              scopeId: tabGroup.id,
              scopeName: tabGroup.title || "",
              color: tabGroup.color,
              totalTabs: sortedTabs.length,
              tabs: sortedTabs.map((t) => ({
                tabId: t.id,
                url: t.url || "",
                title: t.title || "",
                active: t.active || false,
                index: t.index
              }))
            };
            console.log("[ContextEnrichment] 从 Chrome API 获取 Group scope");
          } catch (error2) {
            console.warn("[ContextEnrichment] Chrome API Group 查询失败:", error2);
          }
        }
        if (!relatedTabsInfo) {
          try {
            const allWindowTabs = yield chrome.tabs.query({ windowId: tab.windowId });
            const sortedTabs = allWindowTabs.sort((a, b) => (b.id || 0) - (a.id || 0));
            relatedTabsInfo = {
              scope: "window",
              scopeId: tab.windowId,
              scopeName: "",
              totalTabs: sortedTabs.length,
              tabs: sortedTabs.map((t) => ({
                tabId: t.id,
                url: t.url || "",
                title: t.title || "",
                active: t.active || false,
                index: t.index,
                pinned: t.pinned || false
              }))
            };
            console.log("[ContextEnrichment] 从 Chrome API 获取 Window scope");
          } catch (error2) {
            console.warn("[ContextEnrichment] Chrome API Window 查询失败:", error2);
          }
        }
      }
      let currentTab;
      try {
        currentTab = yield chrome.tabs.get(tabId);
      } catch (error2) {
        console.warn(`[ContextEnrichment] Tab ${tabId} 无法访问:`, error2);
        return result2;
      }
      const contextMeta = __spreadValues(__spreadValues(__spreadValues({
        tabId: currentTab.id,
        url: currentTab.url || "",
        title: currentTab.title || "",
        windowId: currentTab.windowId,
        timestamp: Date.now()
      }, context.chatId && { chatId: context.chatId }), context.sessionId && { sessionId: context.sessionId }), relatedTabsInfo && { relatedTabs: relatedTabsInfo });
      const contextForLLM = {
        currentTab: {
          tabId: currentTab.id,
          url: currentTab.url || "",
          title: currentTab.title || ""
        }
      };
      if (relatedTabsInfo) {
        contextForLLM.relatedTabs = relatedTabsInfo;
      }
      const contextText = formatContextForLLM(contextForLLM);
      const isManoBrowser = true;
      const newContent = [...result2.content];
      if (!isManoBrowser) ;
      return __spreadProps(__spreadValues({}, result2), {
        content: newContent,
        _meta: __spreadProps(__spreadValues({}, result2._meta || {}), {
          context: contextMeta
        })
      });
    } catch (error2) {
      console.warn("[ContextEnrichment] 上下文增强失败:", error2);
      return result2;
    }
  });
  var jsxRuntime = { exports: {} };
  var reactJsxRuntime_production = {};
  var hasRequiredReactJsxRuntime_production;
  function requireReactJsxRuntime_production() {
    if (hasRequiredReactJsxRuntime_production) return reactJsxRuntime_production;
    hasRequiredReactJsxRuntime_production = 1;
    var REACT_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.transitional.element"), REACT_FRAGMENT_TYPE = /* @__PURE__ */ Symbol.for("react.fragment");
    function jsxProd(type2, config2, maybeKey) {
      var key = null;
      void 0 !== maybeKey && (key = "" + maybeKey);
      void 0 !== config2.key && (key = "" + config2.key);
      if ("key" in config2) {
        maybeKey = {};
        for (var propName in config2)
          "key" !== propName && (maybeKey[propName] = config2[propName]);
      } else maybeKey = config2;
      config2 = maybeKey.ref;
      return {
        $$typeof: REACT_ELEMENT_TYPE,
        type: type2,
        key,
        ref: void 0 !== config2 ? config2 : null,
        props: maybeKey
      };
    }
    reactJsxRuntime_production.Fragment = REACT_FRAGMENT_TYPE;
    reactJsxRuntime_production.jsx = jsxProd;
    reactJsxRuntime_production.jsxs = jsxProd;
    return reactJsxRuntime_production;
  }
  var hasRequiredJsxRuntime;
  function requireJsxRuntime() {
    if (hasRequiredJsxRuntime) return jsxRuntime.exports;
    hasRequiredJsxRuntime = 1;
    {
      jsxRuntime.exports = requireReactJsxRuntime_production();
    }
    return jsxRuntime.exports;
  }
  requireJsxRuntime();
  const createStoreImpl = (createState) => {
    let state;
    const listeners = /* @__PURE__ */ new Set();
    const setState = (partial2, replace) => {
      const nextState = typeof partial2 === "function" ? partial2(state) : partial2;
      if (!Object.is(nextState, state)) {
        const previousState = state;
        state = (replace != null ? replace : typeof nextState !== "object" || nextState === null) ? nextState : Object.assign({}, state, nextState);
        listeners.forEach((listener) => listener(state, previousState));
      }
    };
    const getState = () => state;
    const getInitialState = () => initialState;
    const subscribe = (listener) => {
      listeners.add(listener);
      return () => listeners.delete(listener);
    };
    const api = { setState, getState, getInitialState, subscribe };
    const initialState = state = createState(setState, getState, api);
    return api;
  };
  const createStore = ((createState) => createState ? createStoreImpl(createState) : createStoreImpl);
  const identity = (arg) => arg;
  function useStore(api, selector = identity) {
    const slice = React.useSyncExternalStore(
      api.subscribe,
      React.useCallback(() => selector(api.getState()), [api, selector]),
      React.useCallback(() => selector(api.getInitialState()), [api, selector])
    );
    React.useDebugValue(slice);
    return slice;
  }
  const createImpl = (createState) => {
    const api = createStore(createState);
    const useBoundStore = (selector) => useStore(api, selector);
    Object.assign(useBoundStore, api);
    return useBoundStore;
  };
  const create = ((createState) => createImpl);
  create()((set2, get) => ({
    me: {
      user_id: "",
      username: "",
      email: "",
      access_token: ""
    },
    deviceName: "",
    deviceId: "",
    setDeviceId: (deviceId) => {
      set2({ deviceId });
      chrome.storage.local.set({ deviceId });
    },
    setDeviceName: (deviceName) => {
      set2({ deviceName });
      chrome.storage.local.set({ deviceName });
    },
    setMe: (me) => {
      set2({ me });
      chrome.storage.local.set({ userInfo: me });
    },
    initializeDeviceName: () => __async(null, null, function* () {
      try {
        const result2 = yield chrome.storage.local.get("deviceName");
        if (result2.deviceName) {
          set2({ deviceName: result2.deviceName });
        }
      } catch (error2) {
        console.error("Failed to load deviceName from storage:", error2);
      }
    })
  }));
  const CACHE_CONFIG$1 = {
    keyPrefix: "tools_config_cache_",
    ttl: 30 * 60 * 1e3
    // 30分钟 TTL
  };
  const memoryCache = /* @__PURE__ */ new Map();
  function getCacheKey(params = {}) {
    const paramStr = JSON.stringify(params);
    return `${CACHE_CONFIG$1.keyPrefix}${paramStr}`.replace(/[^a-zA-Z0-9_]/g, "_");
  }
  function isCacheValid$1(cache) {
    const now = Date.now();
    return now - cache.timestamp < CACHE_CONFIG$1.ttl;
  }
  function getCacheFromStorage$1(cacheKey) {
    return __async(this, null, function* () {
      try {
        if (isWebEnv()) return null;
        const result2 = yield chrome.storage.local.get(cacheKey);
        return result2[cacheKey] || null;
      } catch (error2) {
        console.error("读取工具配置缓存失败:", error2);
        return null;
      }
    });
  }
  function saveCacheToStorage$1(cacheKey, cache) {
    return __async(this, null, function* () {
      try {
        if (isWebEnv()) return;
        yield chrome.storage.local.set({ [cacheKey]: cache });
        memoryCache.set(cacheKey, cache);
      } catch (error2) {
        console.error("保存工具配置缓存失败:", error2);
      }
    });
  }
  function fetchToolsConfig() {
    return __async(this, arguments, function* (params = {}) {
      try {
        const queryParams = new URLSearchParams();
        if (params.category !== void 0 && params.category !== "") {
          queryParams.append("category", params.category);
        }
        if (params.enabled !== void 0) {
          queryParams.append("enabled", params.enabled.toString());
        }
        const path = "/v1/ui-config/tools";
        const queryString = queryParams.toString();
        const url2 = queryString ? `${path}?${queryString}` : path;
        const response = yield apiRequest$1(url2, {
          method: "GET",
          requireAuth: false,
          showErrorToast: true
        });
        const data = yield response == null ? void 0 : response.json();
        if (!data.data || !Array.isArray(data.data.tools)) {
          throw new Error("API 返回的工具配置信息格式不正确");
        }
        return data;
      } catch (error2) {
        console.error("获取工具配置失败:", error2);
        throw error2;
      }
    });
  }
  function updateToolsConfigCache() {
    return __async(this, arguments, function* (params = {}, options = {}) {
      const { forceUpdate = false, respectTTL = false } = options;
      const cacheKey = getCacheKey(params);
      try {
        if (respectTTL) {
          const cache = memoryCache.get(cacheKey) || (yield getCacheFromStorage$1(cacheKey));
          if (cache && isCacheValid$1(cache)) {
            return cache.tools;
          }
        }
        const response = yield fetchToolsConfig(params);
        const newCache = {
          tools: response.data.tools,
          timestamp: Date.now(),
          params
        };
        yield saveCacheToStorage$1(cacheKey, newCache);
        return response.data.tools;
      } catch (error2) {
        console.error("更新工具配置缓存失败:", error2);
        if (!forceUpdate) {
          const cache = memoryCache.get(cacheKey) || (yield getCacheFromStorage$1(cacheKey));
          if (cache) {
            return cache.tools;
          }
        }
        throw error2;
      }
    });
  }
  function checkDeviceOccupied() {
    return __async(this, null, function* () {
      const deviceId = yield getDeviceId();
      const response = yield apiRequest$1(`/devices/${deviceId}/usage`, {
        method: "GET"
      });
      return response == null ? void 0 : response.json();
    });
  }
  function getUploadSignUrlPost(request) {
    return __async(this, null, function* () {
      const response = yield apiRequest$1("/v1/files/upload-sign-url", {
        method: "POST",
        requireAuth: true,
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify(request),
        showErrorToast: false
        // 不自动显示错误toast，由调用方处理
      });
      const data = yield response == null ? void 0 : response.json();
      if (!data.data || !data.data.uploadUrl) {
        throw new Error("API 返回的预签名URL信息不完整");
      }
      return data;
    });
  }
  function uploadFileToSignedUrl(file2, uploadUrl, options) {
    return __async(this, null, function* () {
      try {
        const controller = new AbortController();
        const timeoutId = setTimeout(
          () => {
            controller.abort();
          },
          5 * 60 * 1e3
        );
        const headers = {
          "Content-Type": file2.type || "application/octet-stream"
        };
        if (options == null ? void 0 : options.filename) {
          headers["x-oss-meta-filename"] = options.filename;
        }
        if (options == null ? void 0 : options.sourceUrl) {
          headers["x-oss-meta-source-url"] = options.sourceUrl;
        }
        const response = yield fetch(uploadUrl, {
          method: "PUT",
          headers,
          body: file2,
          signal: controller.signal
        });
        clearTimeout(timeoutId);
        if (!response.ok) {
          throw new Error(`上传失败: HTTP ${response.status} ${response.statusText}`);
        }
      } catch (error2) {
        if (error2 instanceof Error) {
          if (error2.name === "AbortError") {
            throw new Error("上传超时");
          }
          throw new Error(`上传过程中发生错误: ${error2.message}`);
        }
        throw new Error("上传过程中发生未知错误");
      }
    });
  }
  function uploadFile(file2, options) {
    return __async(this, null, function* () {
      var _a3;
      try {
        const _filename = (options == null ? void 0 : options.filename) || file2.name;
        const contentType = file2.type || "application/octet-stream";
        const signUrlResponse = yield getUploadSignUrlPost({
          filename: encodeURIComponent(_filename),
          purpose: options == null ? void 0 : options.purpose,
          sessionId: options == null ? void 0 : options.sessionId,
          contentType
          // metadata: {
          //   sourceUrl: encodeURIComponent(options?.sourceUrl || ''),
          // },
        });
        if (!signUrlResponse.success) {
          return {
            success: false,
            error: signUrlResponse.message || "获取预签名URL失败"
          };
        }
        yield uploadFileToSignedUrl(file2, signUrlResponse.data.uploadUrl, __spreadProps(__spreadValues({}, options), {
          filename: encodeURIComponent(_filename)
        }));
        return {
          success: true,
          objectKey: signUrlResponse.data.objectKey,
          // OSS 对象键，用于消息传递
          url: (_a3 = signUrlResponse.data.uploadUrl) == null ? void 0 : _a3.split("?")[0]
          // 完整访问URL（保留用于兼容）
        };
      } catch (error2) {
        return {
          success: false,
          error: error2 instanceof Error ? error2.message : "上传失败"
        };
      }
    });
  }
  function getPageContext(options) {
    return __async(this, null, function* () {
      var _a3;
      try {
        const tabs = yield chrome.tabs.query({ active: true, currentWindow: true });
        const currentTab = tabs[0];
        if (!currentTab || !currentTab.id) {
          console.warn("无法获取当前 tab 信息");
          return null;
        }
        const pageContext = {
          url: currentTab.url || "",
          tabId: currentTab.id,
          windowId: currentTab.windowId,
          title: currentTab.title || ""
        };
        if ((options == null ? void 0 : options.includeHtml) && ((_a3 = currentTab.url) == null ? void 0 : _a3.startsWith("http"))) {
          try {
            const results = yield chrome.scripting.executeScript({
              target: { tabId: currentTab.id },
              func: () => document.documentElement.outerHTML
            });
            if (results && results[0] && results[0].result) {
              pageContext.html_content = results[0].result;
            }
          } catch (error2) {
            console.warn("无法获取 HTML 内容:", error2);
          }
        }
        return pageContext;
      } catch (error2) {
        console.error("获取页面上下文失败:", error2);
        return null;
      }
    });
  }
  function getDmBaseUrl() {
    return __async(this, null, function* () {
      const storage = yield chrome.storage.local.get("region_base_url");
      if (storage.region_base_url) {
        return storage.region_base_url;
      }
      return "";
    });
  }
  function fetchLatestSpace(refreshToken, userId) {
    return __async(this, null, function* () {
      var _a3;
      const dmBase = yield getDmBaseUrl();
      const response = yield fetch(
        `${dmBase}/api/auth/user/profile-by-refresh-token?refresh_token=${refreshToken}&user_id=${userId}`,
        {
          method: "GET"
        }
      );
      if (!response.ok) {
        const errorText = yield response.text().catch(() => "Unknown error");
        throw new Error(`HTTP ${response.status}: ${errorText}`);
      }
      const body = yield response.json();
      if (!((_a3 = body == null ? void 0 : body.data) == null ? void 0 : _a3.active_space)) {
        throw new Error("Failed to get active space from response");
      }
      return {
        id: body.data.active_space.id,
        space_name: body.data.active_space.space_name,
        config: body.data.active_space.config,
        subject_id: body.data.active_space.subject_id,
        feature_key: body.data.active_space.feature_key
      };
    });
  }
  function checkSpaceChange() {
    return __async(this, null, function* () {
      var _a3;
      const storage = yield chrome.storage.local.get(["refreshToken", "userInfo"]);
      const refreshToken = storage.refreshToken;
      const userInfo = storage.userInfo;
      if (!refreshToken) {
        return { hasChanged: true };
      }
      try {
        const latestSpace = yield fetchLatestSpace(refreshToken, userInfo == null ? void 0 : userInfo.user_id);
        const currentSpaceId = (_a3 = userInfo == null ? void 0 : userInfo.active_space) == null ? void 0 : _a3.id;
        const hasChanged = currentSpaceId !== latestSpace.id;
        return {
          hasChanged,
          newSpace: latestSpace
        };
      } catch (error2) {
        console.error("[SpaceService] checkSpaceChange error:", error2);
        return { hasChanged: true };
      }
    });
  }
  function createJSONStorage(getStorage, options) {
    let storage;
    try {
      storage = getStorage();
    } catch (e) {
      return;
    }
    const persistStorage = {
      getItem: (name2) => {
        var _a3;
        const parse2 = (str2) => {
          if (str2 === null) {
            return null;
          }
          return JSON.parse(str2, void 0);
        };
        const str = (_a3 = storage.getItem(name2)) != null ? _a3 : null;
        if (str instanceof Promise) {
          return str.then(parse2);
        }
        return parse2(str);
      },
      setItem: (name2, newValue) => storage.setItem(name2, JSON.stringify(newValue, void 0)),
      removeItem: (name2) => storage.removeItem(name2)
    };
    return persistStorage;
  }
  const toThenable = (fn) => (input) => {
    try {
      const result2 = fn(input);
      if (result2 instanceof Promise) {
        return result2;
      }
      return {
        then(onFulfilled) {
          return toThenable(onFulfilled)(result2);
        },
        catch(_onRejected) {
          return this;
        }
      };
    } catch (e) {
      return {
        then(_onFulfilled) {
          return this;
        },
        catch(onRejected) {
          return toThenable(onRejected)(e);
        }
      };
    }
  };
  const persistImpl = (config2, baseOptions) => (set2, get, api) => {
    let options = __spreadValues({
      storage: createJSONStorage(() => localStorage),
      partialize: (state) => state,
      version: 0,
      merge: (persistedState, currentState) => __spreadValues(__spreadValues({}, currentState), persistedState)
    }, baseOptions);
    let hasHydrated = false;
    const hydrationListeners = /* @__PURE__ */ new Set();
    const finishHydrationListeners = /* @__PURE__ */ new Set();
    let storage = options.storage;
    if (!storage) {
      return config2(
        (...args) => {
          console.warn(
            `[zustand persist middleware] Unable to update item '${options.name}', the given storage is currently unavailable.`
          );
          set2(...args);
        },
        get,
        api
      );
    }
    const setItem = () => {
      const state = options.partialize(__spreadValues({}, get()));
      return storage.setItem(options.name, {
        state,
        version: options.version
      });
    };
    const savedSetState = api.setState;
    api.setState = (state, replace) => {
      savedSetState(state, replace);
      return setItem();
    };
    const configResult = config2(
      (...args) => {
        set2(...args);
        return setItem();
      },
      get,
      api
    );
    api.getInitialState = () => configResult;
    let stateFromStorage;
    const hydrate = () => {
      var _a3, _b2;
      if (!storage) return;
      hasHydrated = false;
      hydrationListeners.forEach((cb) => {
        var _a22;
        return cb((_a22 = get()) != null ? _a22 : configResult);
      });
      const postRehydrationCallback = ((_b2 = options.onRehydrateStorage) == null ? void 0 : _b2.call(options, (_a3 = get()) != null ? _a3 : configResult)) || void 0;
      return toThenable(storage.getItem.bind(storage))(options.name).then((deserializedStorageValue) => {
        if (deserializedStorageValue) {
          if (typeof deserializedStorageValue.version === "number" && deserializedStorageValue.version !== options.version) {
            if (options.migrate) {
              const migration = options.migrate(
                deserializedStorageValue.state,
                deserializedStorageValue.version
              );
              if (migration instanceof Promise) {
                return migration.then((result2) => [true, result2]);
              }
              return [true, migration];
            }
            console.error(
              `State loaded from storage couldn't be migrated since no migrate function was provided`
            );
          } else {
            return [false, deserializedStorageValue.state];
          }
        }
        return [false, void 0];
      }).then((migrationResult) => {
        var _a22;
        const [migrated, migratedState] = migrationResult;
        stateFromStorage = options.merge(
          migratedState,
          (_a22 = get()) != null ? _a22 : configResult
        );
        set2(stateFromStorage, true);
        if (migrated) {
          return setItem();
        }
      }).then(() => {
        postRehydrationCallback == null ? void 0 : postRehydrationCallback(stateFromStorage, void 0);
        stateFromStorage = get();
        hasHydrated = true;
        finishHydrationListeners.forEach((cb) => cb(stateFromStorage));
      }).catch((e) => {
        postRehydrationCallback == null ? void 0 : postRehydrationCallback(void 0, e);
      });
    };
    api.persist = {
      setOptions: (newOptions) => {
        options = __spreadValues(__spreadValues({}, options), newOptions);
        if (newOptions.storage) {
          storage = newOptions.storage;
        }
      },
      clearStorage: () => {
        storage == null ? void 0 : storage.removeItem(options.name);
      },
      getOptions: () => options,
      rehydrate: () => hydrate(),
      hasHydrated: () => hasHydrated,
      onHydrate: (cb) => {
        hydrationListeners.add(cb);
        return () => {
          hydrationListeners.delete(cb);
        };
      },
      onFinishHydration: (cb) => {
        finishHydrationListeners.add(cb);
        return () => {
          finishHydrationListeners.delete(cb);
        };
      }
    };
    if (!options.skipHydration) {
      hydrate();
    }
    return stateFromStorage || configResult;
  };
  const persist = persistImpl;
  const chromeStorage = {
    getItem: (name2) => __async(null, null, function* () {
      if (!isExtensionEnv()) return null;
      const result2 = yield chrome.storage.local.get(name2);
      return result2[name2] || null;
    }),
    setItem: (name2, value) => __async(null, null, function* () {
      if (!isExtensionEnv()) return;
      yield chrome.storage.local.set({ [name2]: value });
    }),
    removeItem: (name2) => __async(null, null, function* () {
      if (!isExtensionEnv()) return;
      yield chrome.storage.local.remove(name2);
    })
  };
  const useChatStore = create()(
    persist(
      (set2) => ({
        _hasHydrated: false,
        chatInfo: null,
        // 初始状态为 null，表示新会话
        setChatInfo: (chatInfo) => set2({ chatInfo }),
        updateChatStatus: (status) => set2((state) => ({
          chatInfo: state.chatInfo ? __spreadProps(__spreadValues({}, state.chatInfo), { status }) : null
        })),
        // 消息列表管理
        messages: [],
        addMessage: (message) => set2((state) => {
          const existingIndex = state.messages.findIndex((msg) => msg.id === message.id);
          if (existingIndex !== -1) {
            console.warn("⚠️ 消息 ID 已存在，跳过添加:", message.id);
            return state;
          }
          return { messages: [...state.messages, message] };
        }),
        updateMessage: (messageId, updates) => set2((state) => ({
          messages: state.messages.map(
            (msg) => msg.id === messageId ? __spreadValues(__spreadValues({}, msg), updates) : msg
          )
        })),
        clearMessages: () => set2({ messages: [] }),
        // 完整重置会话（用于新会话按钮）
        resetSession: () => set2(() => ({
          // 重置消息相关
          messages: [],
          streamingMessageId: null,
          // 重置输入相关
          inputMessage: "",
          inputMentionWorkflows: [],
          inputTextDisabled: false,
          inputDisabled: false,
          // 重置页面上下文控制
          showTabInfo: true,
          showWelcome: true,
          // 重置聊天信息为 null，明确表示新会话状态
          chatInfo: null,
          // 重置文件列表
          pendingFiles: []
        })),
        // 流式消息状态
        streamingMessageId: null,
        setStreamingMessageId: (messageId) => set2({ streamingMessageId: messageId }),
        // 输入相关状态
        inputMessage: "",
        setInputMessage: (message) => set2({ inputMessage: message }),
        // 输入框 mention 完整数据（供 editor remount 时还原 displayTitle 等字段）
        inputMentionWorkflows: [],
        setInputMentionWorkflows: (workflows) => set2({ inputMentionWorkflows: workflows }),
        // 页面上下文控制
        showTabInfo: true,
        setShowTabInfo: (show) => set2({ showTabInfo: show }),
        showWelcome: true,
        setShowWelcome: (show) => set2({ showWelcome: show }),
        // 滚动相关
        scrollToBottomRef: null,
        setScrollToBottomRef: (scrollFn) => set2({ scrollToBottomRef: scrollFn }),
        // 文件管理
        pendingFiles: [],
        // 重置录制信息
        recordingInfo: null,
        addPendingFile: (file2) => {
          const fileId = `${Date.now()}_${Math.random().toString(36).substring(2, 11)}_${file2.name}`;
          set2((state) => ({
            pendingFiles: [
              ...state.pendingFiles,
              {
                file: file2,
                id: fileId,
                uploadStatus: "pending"
              }
            ]
          }));
          return fileId;
        },
        removePendingFile: (fileId) => set2((state) => ({
          pendingFiles: state.pendingFiles.filter((f) => f.id !== fileId)
        })),
        updatePendingFileStatus: (fileId, status, objectKey, url2, error2) => set2((state) => ({
          pendingFiles: state.pendingFiles.map(
            (f) => f.id === fileId ? __spreadProps(__spreadValues({}, f), {
              uploadStatus: status,
              objectKey,
              // 存储 OSS objectKey
              url: url2,
              error: error2
            }) : f
          )
        })),
        clearPendingFiles: () => set2({ pendingFiles: [] }),
        // 模式选择
        selectedModelId: "",
        // 初始为空，从 Storage 恢复或用户选择后设置
        setSelectedModelId: (id2) => {
          set2({ selectedModelId: id2 });
        },
        // 当前正在执行的工具（用于 TopBar 实时显示）
        currentTool: null,
        setCurrentTool: (tool) => set2({ currentTool: tool }),
        // 页面背景图片（用于 Web 端展示截图）
        backgroundImage: null,
        setBackgroundImage: (image) => set2({ backgroundImage: image }),
        // 截图轮播相关（用于 Web 端）
        screenshots: [],
        currentScreenshotIndex: 0,
        setScreenshots: (screenshots) => set2({ screenshots }),
        setCurrentScreenshotIndex: (index2) => set2({ currentScreenshotIndex: index2 }),
        setRecordingInfo: (info) => set2({ recordingInfo: info }),
        clearRecordingInfo: () => set2(() => ({
          recordingInfo: null,
          pendingFiles: []
        })),
        // Space 检查失败状态
        spaceCheckFailed: false,
        setSpaceCheckFailed: (failed) => set2({ spaceCheckFailed: failed }),
        // Space 变更确认弹窗状态
        showSpaceConfirmDialog: false,
        setShowSpaceConfirmDialog: (show) => set2({ showSpaceConfirmDialog: show }),
        // 等待中的消息数据（用于 space 确认后继续流程）
        pendingEventData: null,
        setPendingEventData: (data) => set2({ pendingEventData: data })
      }),
      {
        name: "chat-persistence",
        // 存储 key 名
        storage: createJSONStorage(() => chromeStorage),
        // 核心要求：仅持久化 chatInfo 的 id 字段
        partialize: (state) => ({
          chatInfo: state.chatInfo ? { id: state.chatInfo.id } : null
        }),
        onRehydrateStorage: () => (state) => {
          if (state) {
            console.log("[useChatStore] 持久化状态恢复完成");
            state._hasHydrated = true;
          }
        }
      }
    )
  );
  const createMachine = (stateMachineDefinition) => {
    const useStateMachine = create()((set2, get) => ({
      currentState: stateMachineDefinition.initialState,
      eventData: null,
      transition: (event, eventData) => {
        var _a3, _b2, _c2, _d2, _e, _f, _g, _h, _i;
        const currentState = get().currentState;
        const currentStateDefinition = stateMachineDefinition.states[currentState];
        if (!(currentStateDefinition == null ? void 0 : currentStateDefinition.transitions)) {
          console.warn("没有找到当前状态");
          return;
        }
        const destinationTransition = currentStateDefinition.transitions[event];
        if (!destinationTransition) {
          console.warn(`没有找到目标过渡 from ${currentState} to ${event}`);
          return;
        }
        const destinationState = destinationTransition.target;
        if (!destinationState) {
          console.warn("没有找到目标状态");
          return;
        }
        const destinationStateDefinition = stateMachineDefinition.states[destinationState];
        (_a3 = destinationTransition.action) == null ? void 0 : _a3.call(destinationTransition, eventData);
        (_c2 = (_b2 = currentStateDefinition.actions) == null ? void 0 : _b2.beforeExit) == null ? void 0 : _c2.call(_b2, eventData);
        (_e = (_d2 = destinationStateDefinition.actions) == null ? void 0 : _d2.beforeEnter) == null ? void 0 : _e.call(_d2, eventData);
        set2({ currentState: destinationState, eventData });
        (_g = (_f = currentStateDefinition.actions) == null ? void 0 : _f.afterExit) == null ? void 0 : _g.call(_f, eventData);
        (_i = (_h = destinationStateDefinition.actions) == null ? void 0 : _h.afterEnter) == null ? void 0 : _i.call(_h, eventData);
        return destinationState;
      }
    }));
    return useStateMachine;
  };
  class ChatBackgroundAPI {
    constructor() {
      this.port = null;
      this.eventCallback = null;
      this.errorCallback = null;
      this.threadIdCallback = null;
      this.reconnectingSessionId = null;
      this.handleMessage = (response) => {
        var _a3;
        switch (response.type) {
          case "stream_start":
            console.log("Sidepanel: 流式响应开始");
            if (((_a3 = response.payload) == null ? void 0 : _a3.threadId) && this.threadIdCallback) {
              this.threadIdCallback(response.payload.threadId);
            }
            break;
          case "stream_event":
            if (this.eventCallback) {
              this.eventCallback(response.event);
            }
            break;
          case "stream_aborted":
            console.log("Sidepanel: 流式请求被中止");
            this.cleanup();
            break;
          case "error":
            console.error("Sidepanel: 收到错误:", response.error);
            if (this.errorCallback) {
              this.errorCallback(new Error(response.error.message));
            }
            this.cleanup();
            break;
          default:
            console.warn("Sidepanel: 未知的响应类型:", response);
        }
      };
      this.handleDisconnect = () => {
        console.log("Sidepanel: 与 background 的连接已断开");
        if (chrome.runtime.lastError) {
          console.error("Sidepanel: Port 断开连接错误:", chrome.runtime.lastError);
          if (this.errorCallback) {
            this.errorCallback(new Error(chrome.runtime.lastError.message));
          }
        }
        this.cleanup();
      };
    }
    /**
     * 发送流式聊天请求
     * @param params 聊天请求参数
     * @param onEvent 事件回调函数
     * @param onError 错误回调函数
     * @param onThreadId threadId 回调函数，在流式响应开始时立即调用
     */
    sendMessage(params, onEvent, onError, onThreadId) {
      return __async(this, null, function* () {
        try {
          this.eventCallback = onEvent;
          this.errorCallback = onError || null;
          this.threadIdCallback = onThreadId || null;
          this.port = chrome.runtime.connect({ name: "chat-agent" });
          this.port.onMessage.addListener(this.handleMessage);
          this.port.onDisconnect.addListener(this.handleDisconnect);
          const message = {
            type: "send_message",
            params
          };
          this.port.postMessage(message);
          console.log("Sidepanel: 已发送聊天请求到 background");
        } catch (error2) {
          console.error("Sidepanel: 发送消息到 background 失败:", error2);
          this.cleanup();
          throw error2;
        }
      });
    }
    /**
     * 取消当前的流式请求
     */
    abort() {
      if (this.port) {
        const message = {
          type: "abort"
        };
        this.port.postMessage(message);
        console.log("Sidepanel: 已发送中止请求到 background");
      }
      this.cleanup();
    }
    /**
     * 重连到进行中会话的 SSE 流
     * 用于历史会话切换时恢复实时流
     * @param sessionId 会话 ID
     * @param onEvent 事件回调函数
     * @param onError 错误回调函数
     */
    reconnect(sessionId, onEvent, onError) {
      try {
        if (this.reconnectingSessionId === sessionId) {
          console.log(`[ChatBackgroundAPI] 会话 ${sessionId} 已在重连中，忽略重复请求`);
          return;
        }
        if (this.reconnectingSessionId && this.reconnectingSessionId !== sessionId) {
          console.log(
            `[ChatBackgroundAPI] 切换到新会话 ${sessionId}，中止旧重连 ${this.reconnectingSessionId}`
          );
          this.cleanup();
        }
        this.reconnectingSessionId = sessionId;
        this.cleanup();
        this.eventCallback = onEvent;
        this.errorCallback = onError || null;
        this.threadIdCallback = null;
        this.port = chrome.runtime.connect({ name: "chat-agent" });
        this.port.onMessage.addListener(this.handleMessage);
        this.port.onDisconnect.addListener(this.handleDisconnect);
        const message = {
          type: "reconnect_stream",
          sessionId
        };
        this.port.postMessage(message);
        console.log(`[ChatBackgroundAPI] 已发送 SSE 重连请求, sessionId: ${sessionId}`);
      } catch (error2) {
        console.error("[ChatBackgroundAPI] 发送重连请求失败:", error2);
        this.cleanup();
        if (onError) {
          onError(error2 instanceof Error ? error2 : new Error(String(error2)));
        }
      }
    }
    /**
     * 清理资源
     */
    cleanup() {
      if (this.port) {
        this.port.onMessage.removeListener(this.handleMessage);
        this.port.onDisconnect.removeListener(this.handleDisconnect);
        this.port.disconnect();
        this.port = null;
      }
      this.eventCallback = null;
      this.errorCallback = null;
      this.threadIdCallback = null;
      this.reconnectingSessionId = null;
    }
    /**
     * 检查是否有进行中的请求
     */
    isStreaming() {
      return this.port !== null;
    }
  }
  const chatBackgroundAPI = new ChatBackgroundAPI();
  const hasInProgressTodo = (todos) => {
    return Array.isArray(todos) && todos.some((todo) => todo.status === "in_progress");
  };
  const todoWriteRule = {
    name: "TodoWrite",
    priority: 100,
    shouldStartGroup: (toolName, toolInput) => {
      return toolName === TODO_TOOL_NAME && hasInProgressTodo((toolInput == null ? void 0 : toolInput.todos) || []);
    },
    shouldEndGroup: (toolName) => {
      return toolName === TODO_TOOL_NAME;
    },
    includeEndToolInChildren: false,
    needsVirtualParent: false
  };
  const workflowSaverRule = {
    name: "WorkflowSaver",
    priority: 75,
    // 优先级介于 TodoWrite(100) 和 Mano(50) 之间
    shouldStartGroup: (toolName, toolInput) => {
      return toolName === TASK && (toolInput == null ? void 0 : toolInput.subagent_type) === "workflow-saver";
    },
    shouldEndGroup: (toolName) => {
      return toolName === CREATE_WORKFLOW;
    },
    includeEndToolInChildren: true,
    needsVirtualParent: true,
    virtualParentConfig: {
      name: "WorkflowSaver",
      getTodoConfig: () => ({
        content: "保存工作流",
        activeForm: "保存工作流中",
        status: "in_progress"
      })
    }
  };
  const manoRule = {
    name: "Mano",
    priority: 50,
    shouldStartGroup: (toolName) => {
      return toolName === MANO_SUBMIT_TASK;
    },
    shouldEndGroup: (toolName) => {
      return toolName === MANO_SAVE_FILE;
    },
    includeEndToolInChildren: true,
    needsVirtualParent: true,
    virtualParentConfig: {
      name: "Mano",
      getTodoConfig: () => ({
        content: "Mano 数据提取",
        activeForm: "Mano 数据提取",
        status: "in_progress"
      })
    }
  };
  const groupRules = [todoWriteRule, workflowSaverRule, manoRule];
  function findMatchingStartRule(toolName, toolInput) {
    for (const rule of groupRules) {
      if (rule.shouldStartGroup(toolName, toolInput)) {
        return rule;
      }
    }
    return null;
  }
  function findMatchingEndRule(toolName, currentRule) {
    return currentRule.shouldEndGroup(toolName);
  }
  const getTaskStatus = (taskId) => __async(null, null, function* () {
    try {
      const response = yield apiRequest$1(`/v1/mano/task-status/${taskId}`, {
        method: "GET",
        requireAuth: true,
        showErrorToast: false
      });
      return response == null ? void 0 : response.json();
    } catch (error2) {
      console.error("获取任务状态失败:", error2);
      return false;
    }
  });
  const extractMentionWorkflows = (nodes) => {
    const workflows = [];
    const traverse = (nodeList) => {
      nodeList.forEach((n) => {
        if (n.type === "mention" && n.workflowData) {
          workflows.push(__spreadProps(__spreadValues({}, n.workflowData), {
            skill_id: n.workflowData.skill_id || n.workflowData.skillId,
            display_title: n.workflowData.displayTitle
          }));
        }
        if (n.children) {
          traverse(n.children);
        }
      });
    };
    traverse(nodes);
    return workflows;
  };
  let toolsConfigCache = null;
  function clearToolsConfigCache() {
    toolsConfigCache = null;
  }
  function getToolsConfigFromStorage() {
    if (toolsConfigCache) {
      return toolsConfigCache;
    }
    try {
      const webConfigStr = localStorage.getItem("web_tools_config");
      if (webConfigStr) {
        const webConfig = JSON.parse(webConfigStr);
        if (webConfig.tools && webConfig.tools.length > 0) {
          toolsConfigCache = webConfig.tools;
          console.log(
            "✅ [getToolsConfigFromStorage] 从 web_tools_config 加载配置，共",
            webConfig.tools.length,
            "个工具"
          );
          return webConfig.tools;
        }
      }
      const cacheKeys = Object.keys(localStorage).filter(
        (key) => key.startsWith("tools_config_cache_")
      );
      for (const cacheKey of cacheKeys) {
        const cacheStr = localStorage.getItem(cacheKey);
        if (!cacheStr) continue;
        const cache = JSON.parse(cacheStr);
        if (cache.tools && cache.tools.length > 0) {
          toolsConfigCache = cache.tools;
          console.log(
            "✅ [getToolsConfigFromStorage] 从",
            cacheKey,
            "加载配置，共",
            cache.tools.length,
            "个工具"
          );
          return cache.tools;
        }
      }
      console.warn("⚠️ [getToolsConfigFromStorage] 未找到工具配置");
      return [];
    } catch (error2) {
      console.error("❌ [getToolsConfigFromStorage] 读取工具配置失败:", error2);
      return [];
    }
  }
  function deduplicateSkills(workflows) {
    const seen = /* @__PURE__ */ new Set();
    const result2 = [];
    for (const workflow of workflows) {
      const dedupeKey = workflow.skill_id || workflow.skillId || workflow.id;
      if (!dedupeKey) {
        console.warn("发现无效的工作流项（缺少 skillId 和 id）:", workflow);
        continue;
      }
      if (!seen.has(dedupeKey)) {
        seen.add(dedupeKey);
        result2.push(workflow);
      }
    }
    return result2;
  }
  const activeGroupByMessage = /* @__PURE__ */ new Map();
  const toolMap = /* @__PURE__ */ new Map();
  const taskIdMap = /* @__PURE__ */ new Map();
  const pollingMap = /* @__PURE__ */ new Map();
  const TASK_TERMINAL_STATUSES = [
    "completed",
    "failed",
    "error",
    "cancelled",
    "data_completed"
    // Mano 特有的数据完成状态
  ];
  function isTaskTerminal(status) {
    return status ? TASK_TERMINAL_STATUSES.includes(status) : false;
  }
  function pollTaskStatus(taskId, messageId) {
    return __async(this, null, function* () {
      var _a3;
      const instance2 = pollingMap.get(taskId);
      if (!instance2) {
        console.warn(`轮询实例不存在: ${taskId}`);
        return;
      }
      if (instance2.isRequesting) {
        console.log(`轮询跳过（请求中）: ${taskId}`);
        return;
      }
      instance2.isRequesting = true;
      try {
        const result2 = yield getTaskStatus(taskId);
        if (!result2 || typeof result2 !== "object" || !("data" in result2)) {
          console.warn(`获取任务状态失败或返回格式不正确: ${taskId}`);
          return;
        }
        const { data: taskStatus } = result2;
        if (!taskStatus) {
          console.warn(`获取任务状态失败: ${taskId}`);
          return;
        }
        const toolUseId = taskIdMap.get(taskId);
        const toolBlock = toolUseId ? toolMap.get(toolUseId) : null;
        if (!toolBlock) {
          console.warn(`未找到对应的 ToolUseBlock: ${taskId} -> ${toolUseId}`);
          stopTaskPolling(taskId);
          return;
        }
        if (!toolBlock.task) {
          toolBlock.task = { id: taskId };
        }
        toolBlock.task.status = taskStatus.status;
        toolBlock.task.message = taskStatus.status_desc;
        toolBlock.task.elapsed = taskStatus.elapsed;
        const store = useChatStore.getState();
        const message = store.messages.find((msg) => msg.id === messageId);
        if (message == null ? void 0 : message.contentBlocks) {
          store.updateMessage(messageId, {
            contentBlocks: [...message.contentBlocks]
          });
          (_a3 = store.scrollToBottomRef) == null ? void 0 : _a3.call(store);
        }
        if (isTaskTerminal(taskStatus.status)) {
          console.log(`任务已终态，停止轮询: ${taskId} (${taskStatus.status})`);
          stopTaskPolling(taskId);
        }
      } catch (error2) {
        console.error(`轮询任务状态失败: ${taskId}`, error2);
      } finally {
        instance2.isRequesting = false;
      }
    });
  }
  function startTaskPolling(taskId, messageId) {
    if (pollingMap.has(taskId)) {
      console.log(`轮询已存在，跳过启动: ${taskId}`);
      return;
    }
    console.log(`启动任务轮询: ${taskId}`);
    const intervalId = setInterval(() => {
      pollTaskStatus(taskId, messageId);
    }, 3e3);
    pollingMap.set(taskId, {
      taskId,
      messageId,
      intervalId,
      isRequesting: false
    });
    pollTaskStatus(taskId, messageId);
  }
  function stopTaskPolling(taskId) {
    const instance2 = pollingMap.get(taskId);
    if (!instance2) {
      return;
    }
    console.log(`停止任务轮询: ${taskId}`);
    clearInterval(instance2.intervalId);
    pollingMap.delete(taskId);
  }
  function stopAllPolling() {
    if (pollingMap.size === 0) {
      return;
    }
    console.log(`停止所有任务轮询，共 ${pollingMap.size} 个`);
    pollingMap.forEach((instance2) => {
      clearInterval(instance2.intervalId);
    });
    pollingMap.clear();
  }
  function checkTodoWriteCompletionStatus(block, checkTask) {
    var _a3;
    if (block.name === TODO_TOOL_NAME && Array.isArray((_a3 = block.input) == null ? void 0 : _a3.todos)) {
      const hasInProgress = block.input.todos.some((t) => t.status === "in_progress");
      return hasInProgress ? "executed" : "completed";
    }
    if (block.task && checkTask) {
      return "executed";
    }
    return "completed";
  }
  function forceCompleteActiveGroup(messageId, blocks) {
    const activeGroup = activeGroupByMessage.get(messageId);
    if (!activeGroup) return false;
    const parentIndex = blocks.findIndex(
      (b) => b && b.type === "tool_use" && b.id === activeGroup.parentId
    );
    if (parentIndex === -1) return false;
    const parentBlock = blocks[parentIndex];
    parentBlock.status = "completed";
    activeGroupByMessage.delete(messageId);
    return true;
  }
  function checkAndCompleteTodoGroup(messageId, blocks) {
    var _a3;
    const activeGroup = activeGroupByMessage.get(messageId);
    if (!activeGroup || activeGroup.rule.name !== "TodoWrite") return false;
    const parentIndex = blocks.findIndex(
      (b) => b && b.type === "tool_use" && b.id === activeGroup.parentId
    );
    if (parentIndex === -1) return false;
    const parentBlock = blocks[parentIndex];
    if (parentBlock.name === TODO_TOOL_NAME && Array.isArray((_a3 = parentBlock.input) == null ? void 0 : _a3.todos)) {
      const hasInProgress = parentBlock.input.todos.some((t) => t.status === "in_progress");
      if (!hasInProgress) {
        parentBlock.status = "completed";
        activeGroupByMessage.delete(messageId);
        return true;
      }
    }
    return false;
  }
  function handleUnclosedGroupOnStreamEnd(messageId, blocks) {
    const activeGroup = activeGroupByMessage.get(messageId);
    if (!activeGroup) return false;
    const parentIndex = blocks.findIndex(
      (b) => b && b.type === "tool_use" && b.id === activeGroup.parentId
    );
    if (parentIndex === -1) return false;
    const parentBlock = blocks[parentIndex];
    parentBlock.status = "error";
    activeGroupByMessage.delete(messageId);
    console.warn(`SSE 流结束时检测到未闭合的分组: ${activeGroup.rule.name}，已将状态置为 error`);
    return true;
  }
  const chatMachine = createMachine({
    initialState: "idle",
    states: {
      idle: {
        actions: {
          afterEnter: () => __async(null, null, function* () {
            console.log("进入 idle 状态");
            const store = useChatStore.getState();
            store.setStreamingMessageId(null);
          })
        },
        transitions: {
          sendMessage: {
            target: "spaceCheck"
          },
          restoreStreaming: {
            target: "streaming",
            action: () => {
              console.log("状态机：恢复流式传输状态");
            }
          }
        }
      },
      spaceCheck: {
        actions: {
          afterEnter: (eventData) => __async(null, null, function* () {
            console.log("进入 spaceCheck 状态");
            const result2 = yield checkSpaceChange();
            const machineInstance = chatMachine.getState();
            if (result2.hasChanged) {
              machineInstance.transition("requireSpaceConfirmation", eventData);
            } else {
              machineInstance.transition("startDeviceCheck", eventData);
            }
          })
        },
        transitions: {
          requireSpaceConfirmation: {
            target: "spaceConfirmRequired"
          },
          startDeviceCheck: {
            target: "deviceCheck"
          },
          reset: {
            target: "idle"
          }
        }
      },
      spaceConfirmRequired: {
        actions: {
          afterEnter: (eventData) => {
            console.log("进入 spaceConfirmRequired 状态，等待用户确认");
            const store = useChatStore.getState();
            store.setShowSpaceConfirmDialog(true);
            store.setPendingEventData(eventData || null);
          }
        },
        transitions: {
          userConfirmed: {
            target: "deviceCheck"
            // pendingEventData 由 deviceCheck.afterEnter 读取和清除
          },
          userCancelled: {
            target: "idle",
            action: () => {
              const store = useChatStore.getState();
              store.setPendingEventData(null);
            }
          }
        }
      },
      deviceCheck: {
        actions: {
          afterEnter: (eventData) => __async(null, null, function* () {
            console.error("进入 deviceCheck 状态");
            let actualEventData = eventData;
            if (!actualEventData) {
              const store = useChatStore.getState();
              if (store.pendingEventData) {
                actualEventData = store.pendingEventData;
                store.setPendingEventData(null);
                console.log("[deviceCheck] 从 store 恢复 pendingEventData");
              }
            }
            const res = yield checkDeviceOccupied();
            console.error("设备占用检测结果:", res);
            const machineInstance = chatMachine.getState();
            if (res.inUsed && res.service === "DATASAVER") {
              console.error("满足条件，需要用户确认");
              machineInstance.transition("requireConfirmation", actualEventData);
            } else {
              console.error("设备未被占用，直接开始streaming");
              machineInstance.transition("startStreaming", actualEventData);
            }
          })
        },
        transitions: {
          requireConfirmation: {
            target: "confirmRequired"
          },
          startStreaming: {
            target: "streaming"
          },
          reset: {
            target: "idle"
          }
        }
      },
      confirmRequired: {
        actions: {
          afterEnter: (eventData) => {
            console.error("进入 confirmRequired 状态，等待用户确认");
            console.error("确认状态数据:", eventData);
          }
        },
        transitions: {
          userConfirmed: {
            target: "streaming"
          },
          userCancelled: {
            target: "idle"
          }
        }
      },
      streaming: {
        actions: {
          afterEnter: (eventData) => __async(null, null, function* () {
            var _a3, _b2, _c2, _d2, _e, _f, _g;
            console.log("进入 streaming 状态");
            if (!(eventData == null ? void 0 : eventData.message)) {
              console.log("[Streaming] SSE 重连恢复场景，无需发送新消息");
              return;
            }
            getToolsConfigFromStorage();
            const currentStore = useChatStore.getState();
            if (!(eventData == null ? void 0 : eventData.message)) {
              console.error("缺少必要参数");
              return;
            }
            const shouldIncludeContext = (_b2 = (_a3 = eventData.options) == null ? void 0 : _a3.includePageContext) != null ? _b2 : true;
            const shouldIncludeHtml = (_d2 = (_c2 = eventData.options) == null ? void 0 : _c2.includeHtml) != null ? _d2 : true;
            let pageContext;
            if (shouldIncludeContext) {
              pageContext = yield getPageContext({
                includeHtml: shouldIncludeHtml
              });
            }
            const _metadata = __spreadValues(__spreadValues({}, eventData.metadata), pageContext != null ? pageContext : {});
            currentStore.setInputMessage("");
            const uploadedFiles = [];
            try {
              const response = yield chrome.runtime.sendMessage({
                type: BACKGROUND_MESSAGE_TYPES.GET_SUCCESSFUL_REQUESTS
              });
              if ((response == null ? void 0 : response.success) && response.data && response.data.length > 0) {
                const requestsToAttach = response.data.slice(0, LIMITS.MAX_NETWORK_REQUESTS);
                console.log(`自动附加网络请求，共 ${requestsToAttach.length} 个`);
                const jsonData = requestsToAttach.map((req) => ({
                  url: req.url,
                  timestamp: req.timestamp,
                  body: req.responseBody
                }));
                const jsonString = JSON.stringify(jsonData, null, 2);
                const blob = new Blob([jsonString], { type: "application/json" });
                const tabTitle = ((_e = requestsToAttach[0]) == null ? void 0 : _e.tabTitle) || "unknown";
                const timestamp = Date.now();
                const filename = `${CAPTURE_REQUEST_PREFIX}${tabTitle}-${timestamp}.json`;
                const file2 = new File([blob], filename, { type: "application/json" });
                const uploadResult = yield uploadFile(file2, {
                  filename,
                  purpose: "temporary"
                });
                if (uploadResult.success && uploadResult.url) {
                  uploadedFiles.push({
                    type: "document",
                    source: {
                      type: "url",
                      url: uploadResult.url,
                      filename
                    }
                  });
                  console.log("网络请求文件已上传:", filename);
                } else {
                  console.warn("网络请求文件上传失败:", uploadResult.error);
                }
              }
            } catch (error2) {
              console.warn("自动附加网络请求失败:", error2);
            }
            const pendingFiles = currentStore.pendingFiles;
            if (pendingFiles.length > 0) {
              console.log("使用已上传文件，共", pendingFiles.length, "个");
              for (const pendingFile of pendingFiles) {
                if (pendingFile.uploadStatus === "success" && pendingFile.url) {
                  uploadedFiles.push({
                    type: "document",
                    source: {
                      type: "url",
                      url: pendingFile.url,
                      filename: pendingFile.file.name
                    }
                  });
                  console.log("添加文件:", pendingFile.file.name, "url:", pendingFile.url);
                } else if (pendingFile.uploadStatus === "error") {
                  console.warn("存在上传失败的文件，跳过:", pendingFile.file.name);
                }
              }
            }
            let userMessageContent;
            if (uploadedFiles.length > 0) {
              const contentItems = [
                {
                  type: "text",
                  text: eventData.message
                },
                ...uploadedFiles
              ];
              userMessageContent = contentItems;
            } else {
              userMessageContent = eventData.message;
            }
            const mentionedWorkflows = eventData.editorNodes ? extractMentionWorkflows(eventData.editorNodes) : [];
            const deduplicatedSkills = deduplicateSkills(mentionedWorkflows);
            const userMessage = {
              id: `user_${Date.now()}`,
              role: "user",
              content: userMessageContent,
              timestamp: (/* @__PURE__ */ new Date()).toISOString(),
              status: "sent",
              metadata: __spreadValues(__spreadValues({}, _metadata), deduplicatedSkills.length > 0 && { skills: deduplicatedSkills })
            };
            currentStore.addMessage(userMessage);
            if (deduplicatedSkills.length > 0 && currentStore.chatInfo) {
              const existingSessionSkills = ((_f = currentStore.chatInfo.metadata) == null ? void 0 : _f.sessionSkills) || [];
              const updatedSessionSkills = aggregateSkills(existingSessionSkills, deduplicatedSkills);
              currentStore.setChatInfo(__spreadProps(__spreadValues({}, currentStore.chatInfo), {
                metadata: __spreadProps(__spreadValues({}, currentStore.chatInfo.metadata), {
                  sessionSkills: updatedSessionSkills
                })
              }));
            }
            const aiMessage = {
              id: `ai_${Date.now()}`,
              role: "assistant",
              content: "",
              timestamp: (/* @__PURE__ */ new Date()).toISOString(),
              status: "streaming"
            };
            currentStore.addMessage(aiMessage);
            currentStore.setStreamingMessageId(aiMessage.id);
            const messages = [
              // 添加历史消息
              // ...currentStore.messages.map((msg) => ({
              //   role: msg.role,
              //   content: msg.content,
              //   metadata: msg.metadata,
              // })),
              // 添加当前用户消息
              {
                role: "user",
                content: userMessageContent,
                metadata: _metadata,
                command: _metadata == null ? void 0 : _metadata.command
              }
            ];
            try {
              const hasValidMode = currentStore.selectedModelId && currentStore.selectedModelId.trim();
              if (hasValidMode) {
                chrome.storage.local.set({ selectedModelId: currentStore.selectedModelId }).catch((error2) => {
                  console.error("保存模式选择失败:", error2);
                });
              }
              yield chatBackgroundAPI.sendMessage(
                __spreadValues(__spreadValues({
                  chatId: (_g = currentStore == null ? void 0 : currentStore.chatInfo) == null ? void 0 : _g.id,
                  messages,
                  stream: true
                }, hasValidMode && { mode: currentStore.selectedModelId }), deduplicatedSkills.length > 0 && { skills: deduplicatedSkills }),
                (event) => {
                  handleStreamEvent(event, aiMessage.id);
                },
                (error2) => {
                  console.error("流式请求错误:", error2);
                  const store = useChatStore.getState();
                  store.updateMessage(aiMessage.id, {
                    status: "error",
                    content: `错误: ${error2.message}`
                  });
                  const machineInstance = chatMachine.getState();
                  if (machineInstance.currentState === "streaming") {
                    machineInstance.transition("error");
                  } else if (machineInstance.currentState === "aborting") {
                    machineInstance.transition("aborted");
                  }
                },
                (threadId) => __async(null, null, function* () {
                  console.log("Sidepanel: 收到 threadId:", threadId);
                  const store = useChatStore.getState();
                  const currentChatInfo = store.chatInfo;
                  if (currentChatInfo) {
                    store.setChatInfo(__spreadProps(__spreadValues({}, currentChatInfo), {
                      id: threadId
                    }));
                  } else {
                    store.setChatInfo({
                      id: threadId,
                      title: "",
                      createdAt: (/* @__PURE__ */ new Date()).toISOString(),
                      updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
                      status: "running",
                      metadata: {}
                    });
                  }
                  store.clearPendingFiles();
                  console.log("消息发送成功，已清空文件列表");
                  try {
                    yield chrome.runtime.sendMessage({
                      type: BACKGROUND_MESSAGE_TYPES.CLEAR_CAPTURED_REQUESTS
                    });
                    console.log("已清空捕获的网络请求");
                  } catch (error2) {
                    console.warn("清空捕获请求失败:", error2);
                  }
                })
              );
              setTimeout(() => __async(null, null, function* () {
                try {
                  yield updateToolsConfigCache({}, { respectTTL: true });
                  console.log("消息发送时工具配置缓存已检查更新");
                } catch (error2) {
                  console.error("消息发送时更新工具配置失败:", error2);
                }
              }), 0);
            } catch (error2) {
              console.error("发送消息失败:", error2);
              const store = useChatStore.getState();
              store.updateMessage(aiMessage.id, {
                status: "error",
                content: `发送失败: ${error2 instanceof Error ? error2.message : "未知错误"}`
              });
              store.setStreamingMessageId(null);
            }
          })
        },
        transitions: {
          complete: {
            target: "idle"
          },
          error: {
            target: "error"
          },
          abort: {
            target: "aborting",
            action: () => {
              console.log("后端停止请求成功，等待 SSE 确认");
            }
          },
          reset: {
            target: "idle",
            action: () => {
              console.log("强制重置：清理流式状态");
              const store = useChatStore.getState();
              store.setStreamingMessageId(null);
              chatBackgroundAPI == null ? void 0 : chatBackgroundAPI.abort();
              console.log("已中止 SSE 流式请求");
            }
          },
          aborted: {
            target: "idle",
            action: () => {
              console.log("中断已确认，返回 idle 状态");
            }
          }
        }
      },
      aborting: {
        actions: {
          afterEnter: () => {
            console.log("进入 aborting 状态，等待后端确认中断");
          }
        },
        transitions: {
          aborted: {
            target: "idle",
            action: () => {
              console.log("中断已确认，返回 idle 状态");
            }
          },
          resumeStreaming: {
            target: "streaming",
            action: () => {
              console.log("停止失败，SSE 继续发送数据，恢复到 streaming 状态");
            }
          },
          reset: {
            target: "idle",
            action: () => {
              console.log("强制重置：清理流式状态");
              const store = useChatStore.getState();
              store.setStreamingMessageId(null);
              chatBackgroundAPI == null ? void 0 : chatBackgroundAPI.abort();
              console.log("已中止 SSE 流式请求");
            }
          }
        }
      },
      error: {
        actions: {
          afterEnter: () => {
            console.log("进入 error 状态");
            const store = useChatStore.getState();
            store.setStreamingMessageId(null);
            setTimeout(() => {
              const machineInstance = chatMachine.getState();
              if (machineInstance.currentState === "error") {
                machineInstance.transition("reset");
              }
            }, 0);
          }
        },
        transitions: {
          retry: {
            target: "streaming"
          },
          reset: {
            target: "idle"
          }
        }
      }
    }
  });
  function generateCurrentToolState(toolName, toolInput, status = "building", message) {
    var _a3;
    const toolsConfig = getToolsConfigFromStorage();
    const toolConfig = toolsConfig.find(
      (config2) => config2.toolId === toolName || config2.id === toolName || config2.label === toolName
    );
    if (toolConfig) {
      if (!toolConfig.visible || !toolConfig.enabled) {
        return null;
      }
    }
    const ignoredTools = [TODO_TOOL_NAME, ASK_HUMAN, SKILL];
    if (ignoredTools.some((ignored) => toolName.includes(ignored))) {
      return null;
    }
    const shortName = toolName.split("__").pop() || toolName;
    const displayName = (toolConfig == null ? void 0 : toolConfig.label) || getToolCNName(shortName);
    let description2 = "";
    console.log("toolInput", toolInput);
    if (toolInput) {
      const inputPaths = [
        "url",
        "file_path",
        "value",
        "textQuery",
        "keys",
        "description",
        "command",
        "element",
        "user_input"
      ];
      const toolInputConfig = (_a3 = toolConfig == null ? void 0 : toolConfig.parameters) == null ? void 0 : _a3.find((param) => param.visible === true);
      if (toolInputConfig == null ? void 0 : toolInputConfig.name) {
        inputPaths.unshift(toolInputConfig.name);
      }
      let foundValue;
      console.log("🔍 [extractCurrentTool] toolName:", toolName, "toolInput:", toolInput);
      for (const path of inputPaths) {
        const value = toolInput[path];
        console.log(`🔍 [extractCurrentTool] 检查字段 "${path}":`, value, typeof value);
        if (value && typeof value === "string" && value.length > 0) {
          foundValue = value;
          console.log(`✅ [extractCurrentTool] 找到值: "${foundValue}" from field: "${path}"`);
          break;
        }
      }
      if (foundValue) {
        description2 = foundValue;
        console.log("✅ [extractCurrentTool] 最终 description:", description2);
      } else {
        console.warn("⚠️ [extractCurrentTool] 未找到任何值!");
      }
    }
    return {
      toolName: displayName,
      toolFullName: toolName,
      input: "",
      description: description2,
      status,
      message
      // 注意：icon 需要在 UI 层通过 toolConfig 获取，这里不返回
    };
  }
  function handleStreamEvent(event, messageId) {
    var _a3, _b2, _c2, _d2, _e, _f, _g, _h, _i;
    const store = useChatStore.getState();
    const currentMessage = store.messages.find((msg) => msg.id === messageId);
    if (!currentMessage && event.type === "message_start") {
      console.log("[handleStreamEvent] 允许 message_start 事件处理（消息可能正在加载）");
    } else if (!currentMessage && event.type !== "ping") {
      console.log("会话已重置，忽略 SSE 事件:", event.type);
      return;
    }
    const machineInstance = chatMachine.getState();
    if (machineInstance.currentState === "aborting") {
      const streamingEvents = [
        "content_block_start",
        "content_block_delta",
        "content_block_stop",
        "message_delta",
        "tool_result",
        "ping"
      ];
      if (streamingEvents.includes(event.type)) {
        console.log("停止失败：收到流式数据，恢复到 streaming 状态");
        machineInstance.transition("resumeStreaming");
      }
    }
    switch (event.type) {
      case "message_start": {
        console.log("[EventHandler] 收到 message_start 事件:", event);
        const runId = event.message.run_id;
        const threadId = event.message.thread_id;
        const currentMessage2 = store.messages.find((msg) => msg.id === messageId);
        if (currentMessage2) {
          store.updateMessage(messageId, {
            metadata: __spreadProps(__spreadValues({}, currentMessage2.metadata), {
              run_id: runId,
              thread_id: threadId,
              model: event.message.model,
              usage: event.message.usage
            })
          });
          console.log(`[EventHandler] 已存储 run_id: ${runId} 到消息 ${messageId}`);
        }
        const currentChatInfo = store.chatInfo;
        if (currentChatInfo) {
          store.setChatInfo(__spreadProps(__spreadValues({}, currentChatInfo), {
            threadId
          }));
        } else {
          store.setChatInfo({
            id: threadId,
            title: "",
            // 初始标题为空，可以后续更新
            createdAt: (/* @__PURE__ */ new Date()).toISOString(),
            updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
            status: "running",
            metadata: {},
            threadId
          });
        }
        break;
      }
      case "content_block_start": {
        const latestMessage = store.messages.find((msg) => msg.id === messageId);
        if (!latestMessage) return;
        const blocks = latestMessage.contentBlocks ? [...latestMessage.contentBlocks] : [];
        const actualIndex = blocks.length;
        const activeGroup = activeGroupByMessage.get(messageId);
        if (event.content_block.type === "thinking") {
          if (activeGroup) {
            const parentIndex = blocks.findIndex(
              (b) => b && b.type === "tool_use" && b.id === activeGroup.parentId
            );
            if (parentIndex !== -1) {
              const parent = blocks[parentIndex];
              if (!parent.children) parent.children = [];
              const thinkingBlock = {
                type: "thinking",
                index: activeGroup.childrenIndex,
                text: "",
                status: "building"
              };
              parent.children.push(thinkingBlock);
              activeGroup.childrenIndex++;
            } else {
              const topBlock = {
                type: "thinking",
                index: actualIndex,
                text: "",
                status: "building",
                children: [],
                isGroup: true
              };
              blocks.push(topBlock);
            }
          } else {
            const lastBlock = blocks.length > 0 ? blocks[blocks.length - 1] : null;
            if (lastBlock && lastBlock.type === "thinking" && Array.isArray(lastBlock.children)) {
              const childBlock = {
                type: "thinking",
                index: lastBlock.children.length,
                text: "",
                status: "building"
              };
              lastBlock.children.push(childBlock);
            } else {
              const groupBlock = {
                type: "thinking",
                index: actualIndex,
                text: "",
                status: "building",
                children: [],
                isGroup: true
              };
              blocks.push(groupBlock);
            }
          }
        } else if (event.content_block.type === "text") {
          const textBlock = {
            type: "text",
            index: activeGroup ? activeGroup.childrenIndex : actualIndex,
            text: event.content_block.text || ""
          };
          if (activeGroup) {
            const parentIndex = blocks.findIndex(
              (b) => b && b.type === "tool_use" && b.id === activeGroup.parentId
            );
            if (parentIndex !== -1) {
              const parent = blocks[parentIndex];
              if (!parent.children) parent.children = [];
              parent.children.push(textBlock);
              activeGroup.childrenIndex++;
            } else {
              blocks.push(textBlock);
            }
          } else {
            blocks.push(textBlock);
          }
        } else if (event.content_block.type === "tool_use") {
          const toolName = event.content_block.name;
          const toolInput = event.content_block.input;
          if (activeGroup && findMatchingEndRule(toolName, activeGroup.rule)) {
            if (!activeGroup.rule.includeEndToolInChildren) {
              forceCompleteActiveGroup(messageId, blocks);
            }
          }
          const matchedRule = findMatchingStartRule(toolName, toolInput);
          const currentActiveGroup = activeGroupByMessage.get(messageId);
          if (matchedRule) {
            if (currentActiveGroup && currentActiveGroup.rule.priority > matchedRule.priority) {
              const parentIndex = blocks.findIndex(
                (b) => b && b.type === "tool_use" && b.id === currentActiveGroup.parentId
              );
              if (parentIndex !== -1) {
                const parent = blocks[parentIndex];
                if (!parent.children) parent.children = [];
                const childBlock = {
                  type: "tool_use",
                  index: currentActiveGroup.childrenIndex,
                  id: event.content_block.id,
                  name: toolName,
                  input: toolInput,
                  status: "building"
                };
                parent.children.push(childBlock);
                toolMap.set(childBlock.id, childBlock);
                currentActiveGroup.childrenIndex++;
              } else {
                const topBlock = {
                  type: "tool_use",
                  index: actualIndex,
                  id: event.content_block.id,
                  name: toolName,
                  input: toolInput,
                  status: "building"
                };
                blocks.push(topBlock);
                toolMap.set(topBlock.id, topBlock);
              }
            } else {
              forceCompleteActiveGroup(messageId, blocks);
              if (matchedRule.needsVirtualParent && matchedRule.virtualParentConfig) {
                const todoConfig = matchedRule.virtualParentConfig.getTodoConfig();
                const firstChildBlock = {
                  type: "tool_use",
                  index: 0,
                  id: event.content_block.id,
                  name: toolName,
                  input: toolInput,
                  status: "building"
                };
                const virtualParentBlock = {
                  type: "tool_use",
                  index: actualIndex,
                  id: `${matchedRule.name.toLowerCase()}_${event.content_block.id}`,
                  name: matchedRule.virtualParentConfig.name,
                  input: {
                    todos: [
                      {
                        content: todoConfig.content,
                        activeForm: todoConfig.activeForm,
                        status: todoConfig.status
                      }
                    ]
                  },
                  status: "executed",
                  children: [firstChildBlock]
                };
                blocks.push(virtualParentBlock);
                toolMap.set(virtualParentBlock.id, virtualParentBlock);
                toolMap.set(firstChildBlock.id, firstChildBlock);
                activeGroupByMessage.set(messageId, {
                  rule: matchedRule,
                  parentId: virtualParentBlock.id,
                  childrenIndex: 1
                  // 从 1 开始，因为 0 是开始工具
                });
              } else if (matchedRule.name === "TodoWrite") {
                const todoBlock = {
                  type: "tool_use",
                  index: actualIndex,
                  id: event.content_block.id,
                  name: toolName,
                  input: toolInput,
                  status: "building"
                };
                blocks.push(todoBlock);
                toolMap.set(todoBlock.id, todoBlock);
              }
            }
          } else if (currentActiveGroup) {
            const parentIndex = blocks.findIndex(
              (b) => b && b.type === "tool_use" && b.id === currentActiveGroup.parentId
            );
            if (parentIndex !== -1) {
              const parent = blocks[parentIndex];
              if (!parent.children) parent.children = [];
              const childBlock = {
                type: "tool_use",
                index: currentActiveGroup.childrenIndex,
                id: event.content_block.id,
                name: toolName,
                input: toolInput,
                status: "building"
              };
              parent.children.push(childBlock);
              toolMap.set(childBlock.id, childBlock);
              currentActiveGroup.childrenIndex++;
              if (currentActiveGroup.rule.includeEndToolInChildren && findMatchingEndRule(toolName, currentActiveGroup.rule)) {
                parent.status = "completed";
                activeGroupByMessage.delete(messageId);
              }
            } else {
              const topBlock = {
                type: "tool_use",
                index: actualIndex,
                id: event.content_block.id,
                name: toolName,
                input: toolInput,
                status: "building"
              };
              blocks.push(topBlock);
              toolMap.set(topBlock.id, topBlock);
            }
          } else {
            const topBlock = {
              type: "tool_use",
              index: actualIndex,
              id: event.content_block.id,
              name: toolName,
              input: toolInput,
              status: "building"
            };
            blocks.push(topBlock);
            toolMap.set(topBlock.id, topBlock);
          }
        }
        store.updateMessage(messageId, { contentBlocks: blocks });
        (_a3 = store.scrollToBottomRef) == null ? void 0 : _a3.call(store);
        if (event.content_block.type === "tool_use") {
          const toolState = generateCurrentToolState(
            event.content_block.name,
            event.content_block.input,
            "building"
          );
          store.setCurrentTool(toolState);
        }
        break;
      }
      case "content_block_delta": {
        const latestMessage = store.messages.find((msg) => msg.id === messageId);
        if (!latestMessage) return;
        const blocks = latestMessage.contentBlocks ? [...latestMessage.contentBlocks] : [];
        const findLastBuilding = () => {
          for (let i2 = blocks.length - 1; i2 >= 0; i2--) {
            const b = blocks[i2];
            if (!b) continue;
            if (b.type === "thinking" && Array.isArray(b.children) && b.children.length > 0) {
              for (let j = b.children.length - 1; j >= 0; j--) {
                const c = b.children[j];
                if (c && c.type === "thinking" && c.status === "building") {
                  return { scope: "child", parentIndex: i2, childIndex: j, block: c };
                }
              }
            }
            if (b.type === "tool_use" && Array.isArray(b.children) && b.children.length > 0) {
              for (let j = b.children.length - 1; j >= 0; j--) {
                const c = b.children[j];
                if (!c) continue;
                if (c.type === "thinking" && c.status === "building") {
                  return { scope: "child", parentIndex: i2, childIndex: j, block: c };
                }
                if (c.type === "tool_use" && c.status === "building") {
                  return { scope: "child", parentIndex: i2, childIndex: j, block: c };
                }
                if (c.type === "text") {
                  return { scope: "child", parentIndex: i2, childIndex: j, block: c };
                }
              }
            }
            if ((b.type === "text" || b.type === "tool_use" || b.type === "thinking") && b.status === "building") {
              return { scope: "top", index: i2, block: b };
            }
            if (b.type === "text") {
              return { scope: "top", index: i2, block: b };
            }
          }
          return null;
        };
        const last = findLastBuilding();
        if (!last) return;
        const applyUpdate = (updater) => {
          if (last.scope === "top") {
            updater(last.block);
          } else {
            const parent = blocks[last.parentIndex];
            updater(parent.children[last.childIndex]);
          }
        };
        if (event.delta.type === "thinking_delta") {
          const thinking = event.delta.thinking;
          if (last.block && last.block.type === "thinking") {
            applyUpdate((b) => {
              b.text = (b.text || "") + (thinking || "");
            });
            store.updateMessage(messageId, { contentBlocks: blocks });
            (_b2 = store.scrollToBottomRef) == null ? void 0 : _b2.call(store);
          }
        } else if (event.delta.type === "text_delta") {
          const text = event.delta.text;
          if (last.block && last.block.type === "text") {
            applyUpdate((b) => {
              b.text = (b.text || "") + (text || "");
            });
            const allText = blocks.flatMap((b) => (b == null ? void 0 : b.type) === "text" ? [b.text] : []).join("\n\n");
            store.updateMessage(messageId, { contentBlocks: blocks, content: allText });
            (_c2 = store.scrollToBottomRef) == null ? void 0 : _c2.call(store);
          }
        } else if (event.delta.type === "input_json_delta") {
          console.log("🔍 [input_json_delta] 收到输入数据:", event.delta.partial_json);
          const isChild = last.scope === "child";
          const target = isChild ? blocks[last.parentIndex].children[last.childIndex] : last.block;
          console.log("🔍 [input_json_delta] target:", target, "isChild:", isChild);
          if (target && target.type === "tool_use") {
            try {
              target.partialJson = (target.partialJson || "") + event.delta.partial_json;
              console.log("🔍 [input_json_delta] partialJson:", target.partialJson);
              try {
                const parsed = JSON.parse(target.partialJson);
                target.input = parsed;
                console.log("✅ [input_json_delta] 解析成功:", parsed, "target.name:", target.name);
                if (target.name) {
                  console.log("🔄 [input_json_delta] 更新 TopBar...");
                  const toolState = generateCurrentToolState(target.name, parsed, "building");
                  store.setCurrentTool(toolState);
                  console.log("✅ [input_json_delta] TopBar 更新完成:", toolState);
                } else {
                  console.warn(
                    "⚠️ [input_json_delta] 跳过更新 - target.name:",
                    target.name,
                    "isChild:",
                    isChild
                  );
                }
                const todos = (parsed == null ? void 0 : parsed.todos) || [];
                const hasInProgress = Array.isArray(todos) && todos.some((t) => t.status === "in_progress");
                const allPending = Array.isArray(todos) && todos.length > 0 && todos.every((t) => t.status === "pending");
                if (target.name === TODO_TOOL_NAME && allPending) {
                  target.name = `${FE_TOOLS_PREFIX}${TOOL_TODOLIST}`;
                }
                if (target.name === TODO_TOOL_NAME && hasInProgress) {
                  if (!isChild) {
                    const top = last.block;
                    if (!Array.isArray(top.children)) top.children = [];
                    top.group = true;
                    if (typeof top.id === "string") {
                      const matchedRule = findMatchingStartRule(TODO_TOOL_NAME, parsed);
                      if (matchedRule) {
                        activeGroupByMessage.set(messageId, {
                          rule: matchedRule,
                          parentId: top.id,
                          childrenIndex: 0
                        });
                      }
                    }
                  }
                }
                if (target.name === TODO_TOOL_NAME && !isChild) {
                  checkAndCompleteTodoGroup(messageId, blocks);
                }
                if (target.name === TASK && !isChild && (parsed == null ? void 0 : parsed.subagent_type) === "workflow-saver") {
                  const top = last.block;
                  if (!Array.isArray(top.children)) top.children = [];
                  const matchedRule = findMatchingStartRule(TASK, parsed);
                  if (matchedRule && matchedRule.needsVirtualParent && matchedRule.virtualParentConfig && typeof top.id === "string") {
                    const todoConfig = matchedRule.virtualParentConfig.getTodoConfig();
                    top.name = matchedRule.virtualParentConfig.name;
                    top.input = {
                      todos: [
                        {
                          content: todoConfig.content,
                          activeForm: todoConfig.activeForm,
                          status: todoConfig.status
                        }
                      ]
                    };
                    top.status = "executed";
                    activeGroupByMessage.set(messageId, {
                      rule: matchedRule,
                      parentId: top.id,
                      childrenIndex: 0
                    });
                  }
                }
                if (target.name === REPORT_WORKFLOW_PROGRESS && isChild && (parsed == null ? void 0 : parsed.activeForm) && (parsed == null ? void 0 : parsed.status)) {
                  const parent = blocks[last.parentIndex];
                  if (parent && parent.name === "WorkflowSaver" && ((_e = (_d2 = parent.input) == null ? void 0 : _d2.todos) == null ? void 0 : _e[0])) {
                    const currentTodo = parent.input.todos[0];
                    let newStatus;
                    if (parsed.status === "in_progress") {
                      newStatus = "in_progress";
                    } else if (parsed.status === "no_update_needed" || parsed.status === "completed") {
                      newStatus = "completed";
                    } else {
                      newStatus = currentTodo.status;
                    }
                    parent.input.todos[0] = __spreadProps(__spreadValues({}, currentTodo), {
                      activeForm: parsed.activeForm,
                      status: newStatus
                    });
                    if (parsed.status === "no_update_needed") {
                      parent.status = "completed";
                      activeGroupByMessage.delete(messageId);
                      console.log("WorkflowSaver 分组提前结束（no_update_needed）");
                    }
                  }
                }
              } catch (e) {
              }
              store.updateMessage(messageId, { contentBlocks: blocks });
              (_f = store.scrollToBottomRef) == null ? void 0 : _f.call(store);
            } catch (e) {
              console.error("解析工具参数失败:", e);
            }
          }
        }
        break;
      }
      case "content_block_stop": {
        const latestMessage = store.messages.find((msg) => msg.id === messageId);
        if (!latestMessage) return;
        const blocks = latestMessage.contentBlocks ? [...latestMessage.contentBlocks] : [];
        const findLastBuilding = () => {
          for (let i2 = blocks.length - 1; i2 >= 0; i2--) {
            const b = blocks[i2];
            if (!b) continue;
            if (b.type === "thinking" && Array.isArray(b.children) && b.children.length > 0) {
              for (let j = b.children.length - 1; j >= 0; j--) {
                const c = b.children[j];
                if (c && c.type === "thinking" && c.status === "building") {
                  return { scope: "child", parentIndex: i2, childIndex: j, block: c };
                }
              }
            }
            if (b.type === "tool_use" && Array.isArray(b.children) && b.children.length > 0) {
              for (let j = b.children.length - 1; j >= 0; j--) {
                const c = b.children[j];
                if (!c) continue;
                if (c.type === "thinking" && c.status === "building") {
                  return { scope: "child", parentIndex: i2, childIndex: j, block: c };
                }
                if (c.type === "tool_use" && c.status === "building") {
                  return { scope: "child", parentIndex: i2, childIndex: j, block: c };
                }
              }
            }
            if ((b.type === "text" || b.type === "tool_use" || b.type === "thinking") && b.status === "building") {
              return { scope: "top", index: i2, block: b };
            }
          }
          return null;
        };
        const last = findLastBuilding();
        if (!last) return;
        const finish = (b) => {
          if (b.type === "thinking") {
            b.status = "completed";
          } else if (b.type === "tool_use") {
            delete b.partialJson;
            b.status = checkTodoWriteCompletionStatus(b, true);
            if (b.name === TODO_TOOL_NAME && b.status === "completed" && typeof b.id === "string") {
              const activeGroup = activeGroupByMessage.get(messageId);
              if (activeGroup && activeGroup.parentId === b.id) {
                activeGroupByMessage.delete(messageId);
              }
            }
          }
        };
        if (last.scope === "top") {
          finish(last.block);
        } else {
          finish(blocks[last.parentIndex].children[last.childIndex]);
        }
        console.log("content_block_stop:", blocks);
        store.updateMessage(messageId, { contentBlocks: blocks });
        if (last.block.type === "tool_use") {
          const currentTool = store.currentTool;
          if (currentTool) {
            store.setCurrentTool(__spreadProps(__spreadValues({}, currentTool), {
              status: "completed"
            }));
          }
        }
        break;
      }
      case "message_delta":
        console.log("消息增量:", event.delta);
        break;
      case "message_stop": {
        console.log("chat-core消息结束");
        const latestMessage = store.messages.find((msg) => msg.id === messageId);
        if (latestMessage == null ? void 0 : latestMessage.contentBlocks) {
          const blocks = [...latestMessage.contentBlocks];
          if (handleUnclosedGroupOnStreamEnd(messageId, blocks)) {
            store.updateMessage(messageId, { contentBlocks: blocks });
          }
        }
        store.updateMessage(messageId, {
          status: "completed"
        });
        store.updateChatStatus("completed");
        stopAllPolling();
        toolMap.clear();
        taskIdMap.clear();
        store.setCurrentTool(null);
        clearToolsConfigCache();
        const machineInstance2 = chatMachine.getState();
        if (machineInstance2.currentState === "streaming") {
          machineInstance2.transition("complete");
        } else if (machineInstance2.currentState === "aborting") {
          machineInstance2.transition("aborted");
        }
        break;
      }
      case "ping":
        break;
      case "tool_result": {
        const toolBlock = toolMap.get(event.tool_use_id);
        if (toolBlock) {
          toolBlock.status = checkTodoWriteCompletionStatus(toolBlock);
          toolBlock.result = { content: event.content, is_error: event.is_error };
          try {
            const resultText = (_g = event.content[0]) == null ? void 0 : _g.text;
            if (resultText) {
              const resultData = JSON.parse(resultText);
              if ((resultData == null ? void 0 : resultData.task_id) && typeof resultData.task_id === "string" && resultData.status && ["submitted"].includes(resultData.status)) {
                if (!toolBlock.task) {
                  toolBlock.task = { id: resultData.task_id };
                } else {
                  toolBlock.task.id = resultData.task_id;
                }
                if (resultData.status) toolBlock.task.status = resultData.status;
                if (resultData.message) toolBlock.task.message = resultData.message;
                taskIdMap.set(resultData.task_id, toolBlock.id);
                console.log(
                  `tool_result 中建立 task_id 映射: ${resultData.task_id} -> ${toolBlock.id}`
                );
                startTaskPolling(resultData.task_id, messageId);
              }
            }
          } catch (e) {
          }
          if (toolBlock.name === TODO_TOOL_NAME && toolBlock.status === "completed") {
            const activeGroup = activeGroupByMessage.get(messageId);
            if (activeGroup && activeGroup.parentId === toolBlock.id) {
              activeGroupByMessage.delete(messageId);
            }
          }
          const latestMessage = store.messages.find((msg) => msg.id === messageId);
          if (latestMessage == null ? void 0 : latestMessage.contentBlocks) {
            store.updateMessage(messageId, { contentBlocks: [...latestMessage.contentBlocks] });
          }
        } else {
          console.warn("未找到对应的工具调用块 - tool_use_id:", event.tool_use_id);
        }
        break;
      }
      case "skill_invocation": {
        console.log("[skill_invocation]:", event);
        const skill = {
          skill_id: event.skill.skill_id,
          name: event.skill.name,
          display_title: event.skill.display_title,
          description: event.skill.description
        };
        const currentStore = useChatStore.getState();
        if (currentStore.chatInfo) {
          const existingSessionSkills = ((_h = currentStore.chatInfo.metadata) == null ? void 0 : _h.sessionSkills) || [];
          const updatedSessionSkills = aggregateSkills(existingSessionSkills, [skill]);
          currentStore.setChatInfo(__spreadProps(__spreadValues({}, currentStore.chatInfo), {
            metadata: __spreadProps(__spreadValues({}, currentStore.chatInfo.metadata), {
              sessionSkills: updatedSessionSkills
            })
          }));
          console.log("[skill_invocation] sessionSkills updated:", updatedSessionSkills);
        }
        break;
      }
      case "tool_progress": {
        console.log("收到 tool_progress:", event);
        const currentTool = store.currentTool;
        if (currentTool && event.status_desc) {
          store.setCurrentTool(__spreadProps(__spreadValues({}, currentTool), {
            status: "executing",
            message: event.status_desc
          }));
        }
        break;
      }
      // case 'user_message': {
      //   console.log('收到后端中断确认:', event.content);
      //   // 检查并处理未闭合的分组
      //   const latestMessage = store.messages.find((msg) => msg.id === messageId);
      //   if (latestMessage?.contentBlocks) {
      //     const blocks = [...latestMessage.contentBlocks];
      //     if (handleUnclosedGroupOnStreamEnd(messageId, blocks)) {
      //       // 如果有未闭合的分组被设置为 error，更新消息
      //       store.updateMessage(messageId, { contentBlocks: blocks });
      //     }
      //   }
      //   // 只处理消息内容数据
      //   store.updateMessage(messageId, {
      //     status: 'completed',
      //   });
      //   // 触发状态转换，状态机会在 idle.afterEnter 中清理 streamingMessageId
      //   const machineInstance = chatMachine.getState();
      //   machineInstance.transition('aborted'); // → idle.afterEnter 清理
      //   break;
      // }
      case "error": {
        console.error("流式错误:", event.error);
        const latestMessage = store.messages.find((msg) => msg.id === messageId);
        if (latestMessage == null ? void 0 : latestMessage.contentBlocks) {
          const blocks = [...latestMessage.contentBlocks];
          if (handleUnclosedGroupOnStreamEnd(messageId, blocks)) {
            store.updateMessage(messageId, { contentBlocks: blocks });
          }
        }
        store.updateMessage(messageId, {
          status: "error",
          content: `错误: ${(_i = event == null ? void 0 : event.error) == null ? void 0 : _i.message}`
        });
        stopAllPolling();
        toolMap.clear();
        taskIdMap.clear();
        store.updateChatStatus("failed");
        const machineInstance2 = chatMachine.getState();
        if (machineInstance2.currentState === "streaming") {
          machineInstance2.transition("error");
        } else if (machineInstance2.currentState === "aborting") {
          machineInstance2.transition("aborted");
        }
        break;
      }
      default:
        console.log("未知事件类型:", event);
    }
  }
  function aggregateSkills(existingSkills = [], newSkills = []) {
    const skillMap = /* @__PURE__ */ new Map();
    existingSkills.forEach((skill) => {
      const key = skill.skill_id || skill.skillId || skill.id;
      if (key) {
        skillMap.set(key, skill);
      }
    });
    newSkills.forEach((skill) => {
      const key = skill.skill_id || skill.skillId || skill.id;
      if (key && !skillMap.has(key)) {
        skillMap.set(key, skill);
      }
    });
    return Array.from(skillMap.values());
  }
  function sendMessageToTab(tabId, message) {
    return __async(this, null, function* () {
      try {
        return yield chrome.tabs.sendMessage(tabId, message);
      } catch (error2) {
        console.warn(`[AutoScreenshot] 发送消息失败: tabId=${tabId}`, error2);
        return null;
      }
    });
  }
  function captureScreenshot(tabId) {
    return __async(this, null, function* () {
      const timestamp = Date.now();
      const base64Data = yield cdpSessionExecutor.executeWithSession(tabId, (session) => __async(null, null, function* () {
        const result2 = yield session.send("Page.captureScreenshot", {
          format: "webp",
          quality: 80,
          captureBeyondViewport: false
          // 仅可见区域
        });
        return result2.data;
      }));
      return {
        base64: base64Data,
        timestamp
      };
    });
  }
  function generateFilename(context, timestamp) {
    var _a3;
    const toolName = context.toolName.replace(/^chrome_/, "");
    const sessionId = context.sessionId || "no-session";
    const tabId = ((_a3 = context.metadata) == null ? void 0 : _a3.tabId) || "no-tab";
    return `${toolName}_${sessionId}_${tabId}_${timestamp}.webp`;
  }
  function uploadScreenshot(screenshotData, context) {
    return __async(this, null, function* () {
      try {
        const res = yield fetch(`data:image/webp;base64,${screenshotData.base64}`);
        const blob = yield res.blob();
        const filename = generateFilename(context, screenshotData.timestamp);
        const file2 = new File([blob], filename, { type: "image/webp" });
        const uploadResult = yield uploadFile(file2, {
          purpose: "screenshot",
          sessionId: context.sessionId
        });
        if (uploadResult.success) {
          console.log(`[AutoScreenshot] 上传成功: ${filename}`);
        } else {
          console.error(`[AutoScreenshot] 上传失败: ${filename}, 错误: ${uploadResult.error}`);
        }
      } catch (error2) {
        console.error("[AutoScreenshot] 上传过程异常:", error2);
      }
    });
  }
  const SCREENSHOT_TOOL_WHITELIST = /* @__PURE__ */ new Set([
    // 1. 打开网页
    "navigate",
    // 2. 按键操作
    "keyboard",
    // 3. 输入或设置查询条件
    "fill_or_select",
    // 4. 点击
    "click_element",
    // 5. 滚动
    "scroll",
    "scroll_into_view"
  ]);
  function shouldCaptureScreenshot(toolName) {
    const normalizedName = toolName.replace(/^chrome_/, "");
    return SCREENSHOT_TOOL_WHITELIST.has(normalizedName);
  }
  const autoScreenshotMiddleware = (context, next) => __async(null, null, function* () {
    var _a3, _b2;
    const result2 = yield next();
    if (!shouldCaptureScreenshot(context.toolName)) {
      return result2;
    }
    const tabId = ((_a3 = result2._meta) == null ? void 0 : _a3.tabId) || ((_b2 = context == null ? void 0 : context.args) == null ? void 0 : _b2.tabId);
    if (!tabId || !context.sessionId) {
      return result2;
    }
    if (result2.isError) {
      return result2;
    }
    let screenshotData = null;
    try {
      yield sendMessageToTab(tabId, {
        action: "TEMPORARY_DISABLE_OVERLAY",
        duration: 0,
        manual: true
      });
      yield new Promise((resolve2) => setTimeout(resolve2, 50));
      screenshotData = yield captureScreenshot(tabId);
      console.log(
        `[AutoScreenshot] 截图完成: tool=${context.toolName}, tabId=${tabId}, 耗时=${Date.now() - screenshotData.timestamp}ms`
      );
      yield sendMessageToTab(tabId, {
        action: "RESTORE_OVERLAY"
      });
    } catch (error2) {
      yield sendMessageToTab(tabId, { action: "RESTORE_OVERLAY" });
      console.error(`[AutoScreenshot] 截图失败: tool=${context.toolName}, tabId=${tabId}`, error2);
      return result2;
    }
    if (screenshotData) {
      Promise.resolve().then(() => __async(null, null, function* () {
        try {
          yield uploadScreenshot(screenshotData, context);
          console.log(
            "%c ",
            `background-image: url('data:image/webp;base64,${screenshotData.base64}');
           background-size: contain;
           background-repeat: no-repeat;
           padding: 50px 100px;`
            // 通过 padding 撑开显示区域
          );
        } catch (error2) {
          console.error("[AutoScreenshot] 异步上传失败:", error2);
        }
      }));
    }
    return result2;
  });
  const tools = __spreadValues({}, browserTools);
  const toolsMap = new Map(Object.values(tools).map((tool) => [tool.name, tool]));
  for (const tool of Object.values(tools)) {
    registerToolForAutoSchema(tool);
  }
  function createTab(options) {
    return __async(this, null, function* () {
      const { url: url2, active = false, sessionId } = options;
      const lastFocusedWindow = yield chrome.windows.getLastFocused({ populate: false });
      const tab = yield chrome.tabs.create({
        url: url2,
        windowId: lastFocusedWindow.id,
        active
      });
      if (sessionId && tab.id) {
        yield ensureTabInSessionGroup(sessionId, tab.id);
      }
      return tab;
    });
  }
  function getExecutionMetadata(args) {
    return __async(this, null, function* () {
      var _a3;
      try {
        const tabId = args.tabId;
        let url2;
        if (tabId) {
          try {
            const tab = yield chrome.tabs.get(tabId);
            url2 = tab.url;
          } catch (error2) {
          }
        }
        let deviceId;
        try {
          const config2 = yield chrome.storage.local.get(["device_config"]);
          deviceId = (_a3 = config2.device_config) == null ? void 0 : _a3.deviceId;
        } catch (error2) {
        }
        return { tabId: tabId || void 0, url: url2, deviceId };
      } catch (error2) {
        return {};
      }
    });
  }
  const handleCallTool = (param) => __async(null, null, function* () {
    const tool = toolsMap.get(param.name);
    if (!tool) {
      const errorContext = createExecutionContext({
        toolName: param.name,
        args: param.args
      });
      return yield errorHandlerMiddleware(errorContext, () => __async(null, null, function* () {
        throw new Error(`Tool ${param.name} not found`);
      }));
    }
    const metadata2 = yield getExecutionMetadata(param.args);
    const executionContext = createExecutionContext({
      toolName: param.name,
      args: param.args,
      sessionId: param.sessionId,
      metadata: metadata2
    });
    const middlewares = [
      errorHandlerMiddleware,
      // 最外层：捕获所有错误
      tabGroupMiddleware,
      // Tab Group 管理：确保 tab 在 session 的 group 中
      pageProtectionMiddleware,
      // 页面保护：tool 执行期间临时禁用保护
      cdpBackgroundExecutionMiddleware,
      // CDP 后台执行保活：允许后台 Tab 接收 Input 事件
      contextEnrichmentMiddleware,
      // 为返回结果添加页面上下文信息
      autoScreenshotMiddleware
      // Tool执行完成后自动截图并异步上传
    ];
    return yield executeWithMiddleware(executionContext, tool, middlewares);
  });
  function getToolMetadata(toolName) {
    const tool = toolsMap.get(toolName);
    if (!tool) return void 0;
    return {
      annotations: tool.annotations
    };
  }
  const index$3 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
    __proto__: null,
    createTab,
    getToolMetadata,
    handleCallTool
  }, Symbol.toStringTag, { value: "Module" }));
  function initSessionEvents() {
    const sessionManager = getSessionManager();
    getProtectionController().init();
    chrome.storage.onChanged.addListener((changes, areaName) => {
      if (areaName !== "local") return;
      if (!changes[STORAGE_KEY]) return;
      const oldData = changes[STORAGE_KEY].oldValue;
      const newData = changes[STORAGE_KEY].newValue;
      if (!newData) return;
      const oldSessions = (oldData == null ? void 0 : oldData.sessions) || {};
      const newSessions = newData.sessions || {};
      for (const [sessionId, newSession] of Object.entries(newSessions)) {
        const oldSession = oldSessions[sessionId];
        const isNowTerminal = TERMINAL_STATUSES.includes(newSession.status);
        const wasTerminal = oldSession ? oldSession.status !== newSession.status : false;
        if (isNowTerminal && !wasTerminal) {
          console.log(
            `[StorageFallback] 检测到终态: session=${sessionId}, status=${(oldSession == null ? void 0 : oldSession.status) || "unknown"} → ${newSession.status}, tabs=${newSession.tabs.length}`
          );
          for (const tab of newSession.tabs) {
            chrome.tabs.sendMessage(tab.tabId, {
              action: "SET_PROTECTION_MODE",
              mode: "disabled"
            }).catch(() => {
            });
          }
        }
      }
    });
    chrome.tabGroups.onRemoved.addListener((group) => __async(null, null, function* () {
      console.log(`[SessionEvents] Tab group removed: ${group.id}`);
      yield sessionManager.removeSessionByGroupId(group.id);
    }));
    chrome.windows.onRemoved.addListener((windowId) => __async(null, null, function* () {
      console.log(`[SessionEvents] Window removed: ${windowId}`);
      yield sessionManager.removeSessionsByWindowId(windowId);
    }));
    chrome.runtime.onStartup.addListener(() => __async(null, null, function* () {
      console.log("[SessionEvents] Browser startup - clearing all sessions");
      yield sessionManager.clearAllSessions();
    }));
    chrome.tabs.onCreated.addListener((tab) => __async(null, null, function* () {
      if (!tab.id || !tab.groupId || tab.groupId === chrome.tabGroups.TAB_GROUP_ID_NONE) return;
      const session = yield sessionManager.findSessionByTabGroupId(tab.groupId);
      if (!session) return;
      console.log(`[SessionEvents] New tab ${tab.id} detected in session group ${tab.groupId}`);
      yield getProtectionController().protectNewTab(tab.id, session);
      const existingTab = session.tabs.find((t) => t.tabId === tab.id);
      if (!existingTab) {
        yield sessionManager.addTabToSession(session.sessionId, {
          tabId: tab.id,
          url: tab.url || "",
          title: tab.title,
          createdAt: Date.now(),
          lastAccessedAt: Date.now()
        });
      }
    }));
    chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => __async(null, null, function* () {
      if (changeInfo.status !== "complete") return;
      if (!tab.groupId || tab.groupId === chrome.tabGroups.TAB_GROUP_ID_NONE) return;
      const session = yield sessionManager.findSessionByTabGroupId(tab.groupId);
      if (!session) return;
      console.log(`[SessionEvents] Tab ${tabId} refreshed in session group ${tab.groupId}`);
      yield getProtectionController().protectNewTab(tabId, session);
    }));
    console.log("[SessionEvents] Session events initialized");
  }
  function fetchSessionStatus(sessionId) {
    return __async(this, null, function* () {
      try {
        const response = yield apiRequest(`/v1/sessions/${sessionId}/status`, {
          method: "GET",
          requireAuth: true,
          showErrorToast: false
        });
        const data = yield response == null ? void 0 : response.json();
        return (data == null ? void 0 : data.success) ? data : null;
      } catch (error2) {
        console.warn(`[SessionAPI] Failed to fetch status for ${sessionId}:`, error2);
        return null;
      }
    });
  }
  function fetchSessionStatuses(sessionIds) {
    return __async(this, null, function* () {
      const results = yield Promise.allSettled(
        sessionIds.map((id2) => __async(null, null, function* () {
          const response = yield fetchSessionStatus(id2);
          return { sessionId: id2, response };
        }))
      );
      const statusMap = /* @__PURE__ */ new Map();
      for (const result2 of results) {
        if (result2.status === "fulfilled" && result2.value.response) {
          const { sessionId, response } = result2.value;
          statusMap.set(sessionId, response);
        }
      }
      return statusMap;
    });
  }
  function notifyTakeoverStart(sessionId, tabId) {
    return __async(this, null, function* () {
      var _a3;
      try {
        const response = yield apiRequest(`/v1/sessions/${sessionId}/control`, {
          method: "POST",
          requireAuth: true,
          showErrorToast: false,
          body: { action: "takeover", tabId }
        });
        const data = yield response == null ? void 0 : response.json();
        return (_a3 = data == null ? void 0 : data.success) != null ? _a3 : false;
      } catch (error2) {
        console.error(`[SessionAPI] Failed to start takeover for ${sessionId}:`, error2);
        return false;
      }
    });
  }
  function submitTakeoverMessage(sessionId, body) {
    return __async(this, null, function* () {
      var _a3;
      try {
        const response = yield apiRequest(`/v1/sessions/${sessionId}/chat`, {
          method: "POST",
          requireAuth: true,
          showErrorToast: false,
          body
        });
        return (_a3 = response == null ? void 0 : response.ok) != null ? _a3 : false;
      } catch (error2) {
        console.error(`[SessionAPI] Failed to submit takeover message for ${sessionId}:`, error2);
        return false;
      }
    });
  }
  function stopSession(sessionId) {
    return __async(this, null, function* () {
      var _a3;
      try {
        const response = yield apiRequest(`/v1/sessions/${sessionId}/stop`, {
          method: "POST",
          requireAuth: true,
          showErrorToast: false
        });
        const data = yield response == null ? void 0 : response.json();
        return (_a3 = data == null ? void 0 : data.success) != null ? _a3 : false;
      } catch (error2) {
        console.error(`[SessionAPI] Failed to stop session ${sessionId}:`, error2);
        return false;
      }
    });
  }
  const sessionApi = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
    __proto__: null,
    fetchSessionStatus,
    fetchSessionStatuses,
    notifyTakeoverStart,
    stopSession,
    submitTakeoverMessage
  }, Symbol.toStringTag, { value: "Module" }));
  const index$2 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
    __proto__: null,
    BACKEND_STATUS_MAP,
    SESSION_EVENTS,
    STORAGE_KEY,
    clearAllSessions,
    ensureTabInSessionGroup,
    fetchSessionStatus,
    fetchSessionStatuses,
    getProtectionController,
    getSessionManager,
    initSessionEvents,
    loadSessions,
    notifyTakeoverStart,
    saveSessions
  }, Symbol.toStringTag, { value: "Module" }));
  const TOOL_SCHEMAS = getToolSchemas();
  console.log(`[MCP Server] Loaded ${TOOL_SCHEMAS.length} tool schemas (with auto-generation)`);
  let mcpServer = null;
  const getMcpServer = () => {
    if (mcpServer) {
      return mcpServer;
    }
    mcpServer = new Server(
      {
        name: "ChromeExtensionMcpServer",
        version: "1.0.0"
      },
      {
        capabilities: {
          tools: {}
        }
      }
    );
    setupTools(mcpServer);
    return mcpServer;
  };
  const setupTools = (server) => {
    server.setRequestHandler(ListToolsRequestSchema, () => __async(null, null, function* () {
      return {
        tools: TOOL_SCHEMAS
      };
    }));
    server.setRequestHandler(CallToolRequestSchema, (request) => __async(null, null, function* () {
      var _a3;
      console.log("[MCP Server] Tool call request:", request);
      try {
        const sessionId = (_a3 = request.params._meta) == null ? void 0 : _a3.sessionId;
        let isTerminal2 = false;
        if (sessionId) {
          yield getSessionManager().trackSession(sessionId, {
            toolName: request.params.name
          });
          isTerminal2 = yield getSessionManager().isTerminalSession(sessionId);
        }
        const result2 = yield handleCallTool({
          name: request.params.name,
          args: request.params.arguments || {},
          sessionId,
          isTerminal: isTerminal2
        });
        console.log("[MCP Server] Tool call result:", result2);
        return result2;
      } catch (error2) {
        return {
          content: [
            {
              type: "text",
              text: `Error calling tool: ${error2 instanceof Error ? error2.message : String(error2)}`
            }
          ],
          isError: true
        };
      }
    }));
  };
  class ActivityBasedHeartbeat {
    constructor(config2, callbacks) {
      __publicField2(this, "ws", null);
      __publicField2(this, "config");
      __publicField2(this, "callbacks");
      __publicField2(this, "heartbeatTimer", null);
      __publicField2(this, "activityTimer", null);
      __publicField2(this, "messageListener");
      __publicField2(this, "lastActivityTime", 0);
      __publicField2(this, "latencyMetrics", {
        current: 0,
        average: 0,
        min: Infinity,
        max: 0,
        samples: [],
        lastUpdate: 0
      });
      this.config = config2;
      this.callbacks = callbacks;
    }
    /**
     * 绑定 WebSocket 并开始心跳检测
     */
    start(websocket) {
      if (this.heartbeatTimer) {
        console.warn("[ActivityHeartbeat] 心跳已在运行，先停止旧的");
        this.stop();
      }
      this.ws = websocket;
      this.setupMessageListener();
      this.startHeartbeatTimer();
      console.log(
        `[ActivityHeartbeat] 启动心跳检测，间隔: ${this.config.interval}ms, 超时: ${this.config.timeout}ms`
      );
    }
    /**
     * 停止心跳检测
     */
    stop() {
      this.clearTimers();
      this.removeMessageListener();
      this.lastActivityTime = 0;
      this.ws = null;
      console.log("[ActivityHeartbeat] 停止心跳检测");
    }
    /**
     * 手动发送 ping 测试延迟
     */
    sendManualPing() {
      var _a3, _b2;
      if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
        return false;
      }
      try {
        const pingId = `manual_ping_${Date.now()}`;
        this.ws.send(JSON.stringify({ id: pingId, type: "ping" }));
        (_b2 = (_a3 = this.callbacks).onPingSend) == null ? void 0 : _b2.call(_a3, pingId);
        return true;
      } catch (error2) {
        console.error("[ActivityHeartbeat] 手动 ping 发送失败:", error2);
        return false;
      }
    }
    /**
     * 获取延迟统计
     */
    getLatencyMetrics() {
      return __spreadValues({}, this.latencyMetrics);
    }
    /**
     * 重置延迟统计
     */
    resetLatencyMetrics() {
      this.latencyMetrics = {
        current: 0,
        average: 0,
        min: Infinity,
        max: 0,
        samples: [],
        lastUpdate: 0
      };
    }
    /**
     * 设置消息监听器 - 监听所有消息来判断连接活跃度
     */
    setupMessageListener() {
      if (!this.ws) return;
      this.messageListener = (event) => {
        this.resetActivityTimer();
        try {
          const data = JSON.parse(event.data);
          if (data.type === "pong") {
            this.handlePongMessage(data);
          }
        } catch (_) {
        }
      };
      this.ws.addEventListener("message", this.messageListener);
    }
    removeMessageListener() {
      if (this.ws && this.messageListener) {
        this.ws.removeEventListener("message", this.messageListener);
        this.messageListener = void 0;
      }
    }
    /**
     * 启动心跳定时器 - 定期发送 ping
     */
    startHeartbeatTimer() {
      this.lastActivityTime = Date.now();
      this.resetActivityTimer();
      this.heartbeatTimer = setInterval(() => {
        this.sendHeartbeatPing();
      }, this.config.interval);
    }
    /**
     * 发送心跳 ping
     */
    sendHeartbeatPing() {
      var _a3, _b2;
      if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
        console.warn("[ActivityHeartbeat] WebSocket 不可用，触发超时重连");
        this.callbacks.onTimeout();
        return;
      }
      try {
        const pingId = `heartbeat_${Date.now()}`;
        this.ws.send(
          JSON.stringify({
            id: pingId,
            type: "ping"
          })
        );
        (_b2 = (_a3 = this.callbacks).onPingSend) == null ? void 0 : _b2.call(_a3, pingId);
      } catch (error2) {
        console.error("[ActivityHeartbeat] ping 发送失败:", error2);
        this.callbacks.onTimeout();
      }
    }
    /**
     * 重置活跃计时器
     * 核心逻辑：收到任何消息时调用，重新开始超时倒计时
     */
    resetActivityTimer() {
      this.lastActivityTime = Date.now();
      this.clearActivityTimer();
      this.activityTimer = setTimeout(() => {
        console.warn(`[ActivityHeartbeat] 连接超时，${this.config.timeout}ms 内未收到任何消息`);
        this.callbacks.onTimeout();
      }, this.config.timeout);
    }
    /**
     * 处理 pong 消息，计算延迟
     */
    handlePongMessage(pongData) {
      var _a3, _b2;
      const pongId = pongData.id;
      if (!pongId) return;
      const latency = this.calculateLatency(pongId);
      if (latency >= 0) {
        this.updateLatencyMetrics(latency);
        this.callbacks.onLatencyUpdate(latency);
        (_b2 = (_a3 = this.callbacks).onPongReceived) == null ? void 0 : _b2.call(_a3, pongId, latency);
      }
    }
    calculateLatency(pingId) {
      try {
        const timestampStr = pingId.replace(/^(heartbeat_|manual_ping_|ext_ping_)/, "");
        const pingTime = parseInt(timestampStr, 10);
        if (isNaN(pingTime)) {
          console.warn("[ActivityHeartbeat] 无法解析 ping 时间戳:", pingId);
          return -1;
        }
        return Date.now() - pingTime;
      } catch (error2) {
        console.error("[ActivityHeartbeat] 延迟计算失败:", error2);
        return -1;
      }
    }
    updateLatencyMetrics(latency) {
      const now = Date.now();
      this.latencyMetrics.current = latency;
      this.latencyMetrics.lastUpdate = now;
      this.latencyMetrics.samples.push(latency);
      if (this.latencyMetrics.samples.length > 50) {
        this.latencyMetrics.samples.shift();
      }
      const samples = this.latencyMetrics.samples;
      this.latencyMetrics.min = Math.min(...samples);
      this.latencyMetrics.max = Math.max(...samples);
      this.latencyMetrics.average = Math.round(
        samples.reduce((sum, val) => sum + val, 0) / samples.length
      );
    }
    clearTimers() {
      this.clearHeartbeatTimer();
      this.clearActivityTimer();
    }
    clearHeartbeatTimer() {
      if (this.heartbeatTimer) {
        clearInterval(this.heartbeatTimer);
        this.heartbeatTimer = null;
      }
    }
    clearActivityTimer() {
      if (this.activityTimer) {
        clearTimeout(this.activityTimer);
        this.activityTimer = null;
      }
    }
  }
  class WebSocketConnectionManager {
    constructor(config2, callbacks) {
      __publicField2(this, "ws", null);
      __publicField2(this, "config");
      __publicField2(this, "callbacks");
      __publicField2(this, "url", "");
      __publicField2(this, "connected", false);
      __publicField2(this, "reconnectAttempts", 0);
      __publicField2(this, "reconnectTimer", null);
      __publicField2(this, "shouldReconnect", true);
      this.config = config2;
      this.callbacks = callbacks;
    }
    /**
     * 连接到指定 URL
     */
    connect(url2) {
      return __async(this, null, function* () {
        var _a3;
        if (this.connected && this.url === url2 && ((_a3 = this.ws) == null ? void 0 : _a3.readyState) === WebSocket.OPEN) {
          console.log("[ConnectionManager] 已连接到相同 URL，跳过重连");
          return;
        }
        if (this.ws) {
          yield this.disconnect();
        }
        this.url = url2;
        this.shouldReconnect = true;
        yield this.performConnect();
      });
    }
    /**
     * 断开连接（主动断开，不会重连）
     */
    disconnect() {
      return __async(this, null, function* () {
        console.log("[ConnectionManager] 主动断开连接");
        this.shouldReconnect = false;
        this.cancelReconnect();
        if (this.ws) {
          yield this.closeWebSocket();
        }
        this.connected = false;
        this.reconnectAttempts = 0;
      });
    }
    /**
     * 强制重连（用于外部触发，如心跳超时）
     */
    forceReconnect(reason = "外部触发") {
      return __async(this, null, function* () {
        console.log(`[ConnectionManager] 强制重连，原因: ${reason}`);
        if (this.ws) {
          yield this.closeWebSocket();
        }
        this.connected = false;
        if (this.shouldReconnect) {
          this.scheduleReconnect();
        }
      });
    }
    /**
     * 获取连接状态
     */
    getStatus() {
      var _a3, _b2;
      return {
        connected: this.connected,
        url: this.url,
        reconnectAttempts: this.reconnectAttempts,
        wsState: (_b2 = (_a3 = this.ws) == null ? void 0 : _a3.readyState) != null ? _b2 : WebSocket.CLOSED
      };
    }
    /**
     * 获取当前 WebSocket 实例（仅用于只读操作）
     */
    getWebSocket() {
      return this.ws;
    }
    /**
     * 设置是否允许自动重连
     */
    setAutoReconnect(enabled) {
      this.shouldReconnect = enabled;
      if (!enabled) {
        this.cancelReconnect();
      }
    }
    performConnect() {
      return __async(this, null, function* () {
        return new Promise((resolve2, reject) => {
          try {
            console.log(`[ConnectionManager] 连接到: ${this.url}`);
            const ws = new WebSocket(this.url);
            this.ws = ws;
            ws.onopen = () => {
              console.log("[ConnectionManager] ✅ WebSocket 连接成功");
              this.connected = true;
              this.reconnectAttempts = 0;
              this.callbacks.onConnected(ws);
              resolve2();
            };
            ws.onclose = (event) => {
              console.log(`[ConnectionManager] 🔌 连接关闭，代码: ${event.code}`);
              this.handleConnectionLoss("连接关闭");
            };
            ws.onerror = (error2) => {
              console.error("[ConnectionManager] ❌ 连接错误:", error2);
              if (ws.readyState === WebSocket.CONNECTING) {
                reject(new Error("WebSocket 连接失败"));
              } else {
                this.handleConnectionLoss("连接错误");
              }
            };
          } catch (error2) {
            reject(error2);
          }
        });
      });
    }
    closeWebSocket() {
      return __async(this, null, function* () {
        if (!this.ws) return;
        const ws = this.ws;
        this.ws = null;
        ws.onclose = null;
        ws.onerror = null;
        if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) {
          yield new Promise((resolve2) => {
            const closeHandler = () => {
              ws.removeEventListener("close", closeHandler);
              resolve2();
            };
            ws.addEventListener("close", closeHandler);
            ws.close();
            setTimeout(resolve2, 1e3);
          });
        }
      });
    }
    handleConnectionLoss(reason) {
      const wasConnected = this.connected;
      this.connected = false;
      this.ws = null;
      if (wasConnected) {
        this.callbacks.onDisconnected(reason);
        if (this.shouldReconnect) {
          this.scheduleReconnect();
        }
      }
    }
    scheduleReconnect() {
      if (this.config.maxReconnectAttempts !== -1 && this.reconnectAttempts >= this.config.maxReconnectAttempts) {
        console.log("[ConnectionManager] 达到最大重连次数，停止重连");
        this.callbacks.onReconnectFailed(this.reconnectAttempts);
        return;
      }
      this.cancelReconnect();
      this.reconnectAttempts++;
      console.log(
        `[ConnectionManager] 🔄 ${this.config.reconnectDelay}ms 后进行第 ${this.reconnectAttempts} 次重连...`
      );
      this.callbacks.onReconnecting(this.reconnectAttempts);
      this.reconnectTimer = setTimeout(() => __async(this, null, function* () {
        this.reconnectTimer = null;
        try {
          yield this.performConnect();
        } catch (error2) {
          console.error("[ConnectionManager] 重连失败:", error2);
          if (this.shouldReconnect) {
            this.scheduleReconnect();
          }
        }
      }), this.config.reconnectDelay);
    }
    cancelReconnect() {
      if (this.reconnectTimer) {
        clearTimeout(this.reconnectTimer);
        this.reconnectTimer = null;
      }
    }
  }
  class WebSocketMcpClient {
    constructor(config2) {
      __publicField2(this, "connectionManager");
      __publicField2(this, "heartbeatDetector");
      __publicField2(this, "transport", null);
      __publicField2(this, "config");
      this.config = __spreadValues({
        reconnectDelay: 1e3,
        maxReconnectAttempts: -1,
        heartbeatInterval: 2e3,
        heartbeatTimeout: 5e3
      }, config2);
      this.connectionManager = new WebSocketConnectionManager(
        {
          reconnectDelay: this.config.reconnectDelay,
          maxReconnectAttempts: this.config.maxReconnectAttempts
        },
        this.createConnectionCallbacks()
      );
      this.heartbeatDetector = new ActivityBasedHeartbeat(
        {
          interval: this.config.heartbeatInterval,
          timeout: this.config.heartbeatTimeout
        },
        this.createHeartbeatCallbacks()
      );
    }
    start(url2) {
      return __async(this, null, function* () {
        console.log("[WebSocket MCP] 启动客户端，URL:", url2);
        yield this.connectionManager.connect(url2);
      });
    }
    stop() {
      return __async(this, null, function* () {
        console.log("[WebSocket MCP] 停止客户端");
        this.heartbeatDetector.stop();
        if (this.transport) {
          yield this.transport.close();
          this.transport = null;
        }
        yield this.connectionManager.disconnect();
      });
    }
    getStatus() {
      const connectionStatus = this.connectionManager.getStatus();
      const latencyMetrics = this.heartbeatDetector.getLatencyMetrics();
      return __spreadProps(__spreadValues({}, connectionStatus), {
        latency: latencyMetrics
      });
    }
    getLatencyMetrics() {
      return this.heartbeatDetector.getLatencyMetrics();
    }
    triggerLatencyTest() {
      return this.heartbeatDetector.sendManualPing();
    }
    /**
     * 创建连接管理器回调
     */
    createConnectionCallbacks() {
      return {
        onConnected: (websocket) => __async(this, null, function* () {
          try {
            this.transport = new WebSocketTransport(websocket);
            const mcpServer2 = getMcpServer();
            yield mcpServer2.connect(this.transport);
            this.heartbeatDetector.start(websocket);
            Promise.resolve().then(() => index$2).then(({ getSessionManager: getSessionManager2 }) => {
              getSessionManager2().onWebSocketConnected();
            });
          } catch (error2) {
            console.error("[WebSocket MCP] MCP Server 连接失败:", error2);
            throw error2;
          }
        }),
        onDisconnected: (reason) => {
          console.log(`[WebSocket MCP] 连接断开: ${reason}`);
          this.heartbeatDetector.stop();
          if (this.transport) {
            this.transport.close().catch(console.error);
            this.transport = null;
          }
        },
        onReconnecting: (attempt) => {
          console.log(`[WebSocket MCP] 正在重连，第 ${attempt} 次尝试`);
          this.heartbeatDetector.stop();
        },
        onReconnectFailed: (finalAttempt) => {
          console.log(`[WebSocket MCP] 重连失败，共尝试 ${finalAttempt} 次`);
          this.heartbeatDetector.stop();
        }
      };
    }
    /**
     * 创建心跳检测器回调
     */
    createHeartbeatCallbacks() {
      return {
        onTimeout: () => {
          console.warn("[WebSocket MCP] 心跳超时，触发强制重连");
          this.connectionManager.forceReconnect("心跳超时").catch(console.error);
        },
        onLatencyUpdate: (latency) => {
          this.broadcastLatencyUpdate(latency);
        },
        onPingSend: (pingId) => {
        },
        onPongReceived: (pongId, latency) => {
        }
      };
    }
    /**
     * 广播延迟更新到扩展的其他部分
     */
    broadcastLatencyUpdate(latency) {
      const connectionStatus = this.connectionManager.getStatus();
      chrome.runtime.sendMessage({
        type: BACKGROUND_MESSAGE_TYPES$1.WEBSOCKET_LATENCY_UPDATED,
        payload: {
          latencyMetrics: this.heartbeatDetector.getLatencyMetrics(),
          connected: connectionStatus.connected
        }
      }).catch(() => {
      });
    }
  }
  const service = new WebSocketMcpClient();
  function startWebSocketMCP(url2) {
    return __async(this, null, function* () {
      return service.start(url2);
    });
  }
  function stopWebSocketMCP() {
    return __async(this, null, function* () {
      console.log("[WebSocket MCP] 停止服务");
      yield service.stop();
    });
  }
  function getWebSocketMCPStatus() {
    return service.getStatus();
  }
  function getWebSocketLatencyMetrics() {
    return service.getLatencyMetrics();
  }
  function triggerWebSocketLatencyTest() {
    return service.triggerLatencyTest();
  }
  let currentWebSocketUrl = null;
  let listenerRegistered = false;
  function getDeviceConfig() {
    return __async(this, null, function* () {
      try {
        const result2 = yield chrome.storage.local.get(["device_config"]);
        return result2.device_config || null;
      } catch (error2) {
        console.error("[WebSocket MCP] 获取设备配置失败:", error2);
        return null;
      }
    });
  }
  function buildWebSocketUrl(config2) {
    return `${config2.websocketUrl}?apiKey=${config2.token}`;
  }
  const initWebSocketMCPListener = () => __async(null, null, function* () {
    setupConfigChangeListener();
    const config2 = yield getDeviceConfig();
    if (!config2) {
      console.log("[WebSocket MCP] 未找到设备配置，等待用户配置");
      return;
    }
    const websocketUrl = buildWebSocketUrl(config2);
    if (currentWebSocketUrl === websocketUrl && getWebSocketMCPStatus().connected) {
      return;
    }
    currentWebSocketUrl = websocketUrl;
    yield startWebSocketMCP(websocketUrl);
  });
  function setupConfigChangeListener() {
    if (listenerRegistered) return;
    listenerRegistered = true;
    chrome.storage.onChanged.addListener((changes, namespace) => __async(null, null, function* () {
      if (namespace === "local" && changes.device_config) {
        console.log("[WebSocket MCP] 检测到设备配置变化");
        const newConfig = changes.device_config.newValue;
        if (!newConfig) {
          console.log("[WebSocket MCP] 配置已删除，停止连接");
          yield stopWebSocketMCPListener();
          return;
        }
        const newWebSocketUrl = buildWebSocketUrl(newConfig);
        if (currentWebSocketUrl !== newWebSocketUrl) {
          console.log("[WebSocket MCP] WebSocket URL 已变化，重新连接");
          console.log("[WebSocket MCP] 旧 URL:", currentWebSocketUrl);
          console.log("[WebSocket MCP] 新 URL:", newWebSocketUrl);
          currentWebSocketUrl = newWebSocketUrl;
          yield startWebSocketMCP(newWebSocketUrl);
        }
      }
    }));
  }
  const stopWebSocketMCPListener = () => __async(null, null, function* () {
    stopWebSocketMCP();
    currentWebSocketUrl = null;
  });
  const getMCPStatus = () => {
    return getWebSocketMCPStatus();
  };
  function handleGetWebSocketLatencyMetrics() {
    return __async(this, null, function* () {
      try {
        const latencyMetrics = getWebSocketLatencyMetrics();
        const status = getWebSocketMCPStatus();
        return {
          success: true,
          latencyMetrics,
          connected: status.connected
        };
      } catch (error2) {
        console.error("Background: Failed to get WebSocket latency metrics:", error2);
        return {
          success: false,
          error: error2.message
        };
      }
    });
  }
  const initWebSocketLatencyListener = () => {
    console.log("Background: Initializing WebSocket latency listener");
    chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
      if (message.type === BACKGROUND_MESSAGE_TYPES$1.GET_WEBSOCKET_LATENCY_METRICS) {
        handleGetWebSocketLatencyMetrics().then((result2) => sendResponse(result2)).catch((error2) => sendResponse({ success: false, error: error2.message }));
        return true;
      }
      if (message.type === BACKGROUND_MESSAGE_TYPES$1.TRIGGER_WEBSOCKET_LATENCY_TEST) {
        try {
          const triggered = triggerWebSocketLatencyTest();
          sendResponse({ success: triggered });
        } catch (error2) {
          sendResponse({ success: false, error: error2.message });
        }
        return true;
      }
    });
  };
  function fetchImageAsBase64(_0) {
    return __async(this, arguments, function* (url2, headers = {}) {
      try {
        if (!url2) {
          return {
            success: false,
            error: "URL parameter is required"
          };
        }
        const response = yield fetch(url2, {
          method: "GET",
          headers: __spreadValues({
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
          }, headers)
        });
        if (!response.ok) {
          throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        const blob = yield response.blob();
        return new Promise((resolve2) => {
          const reader = new FileReader();
          reader.onload = () => {
            resolve2({
              success: true,
              data: reader.result,
              contentType: blob.type,
              size: blob.size
            });
          };
          reader.onerror = () => {
            resolve2({
              success: false,
              error: "Failed to read image data"
            });
          };
          reader.readAsDataURL(blob);
        });
      } catch (error2) {
        return {
          success: false,
          error: error2 instanceof Error ? error2.message : "Unknown error occurred"
        };
      }
    });
  }
  function initImageFetcherListener() {
    chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
      if (message && message.type === BACKGROUND_MESSAGE_TYPES$1.FETCH_IMAGE_URL) {
        (() => __async(null, null, function* () {
          const { url: url2, headers } = message;
          const result2 = yield fetchImageAsBase64(url2, headers);
          sendResponse(result2);
        }))();
        return true;
      }
    });
  }
  const BASE_RULE_ID = 1e5;
  const PLATFORM_REFERER_RULES = [
    {
      domain: "weibo.com",
      referer: "https://weibo.com/",
      ruleId: BASE_RULE_ID + 1
    }
  ];
  function initBackgroundRequestModifier() {
    return __async(this, null, function* () {
      try {
        yield clearAllRefererRules();
        const rules2 = PLATFORM_REFERER_RULES.map((config2) => ({
          id: config2.ruleId,
          priority: 1,
          action: {
            type: chrome.declarativeNetRequest.RuleActionType.MODIFY_HEADERS,
            requestHeaders: [
              {
                header: "Referer",
                operation: chrome.declarativeNetRequest.HeaderOperation.SET,
                value: config2.referer
              }
            ]
          },
          condition: {
            // 只匹配来自扩展自身的请求
            initiatorDomains: [chrome.runtime.id],
            // 匹配目标域名
            requestDomains: [config2.domain],
            resourceTypes: [
              chrome.declarativeNetRequest.ResourceType.XMLHTTPREQUEST,
              chrome.declarativeNetRequest.ResourceType.OTHER
            ]
          }
        }));
        if (rules2.length > 0) {
          yield chrome.declarativeNetRequest.updateDynamicRules({
            addRules: rules2
          });
          console.log("[BackgroundRequestModifier] 已添加 background 请求头修改规则:", rules2.length);
          console.log("[BackgroundRequestModifier] 扩展 ID:", chrome.runtime.id);
        }
      } catch (error2) {
        console.error("[BackgroundRequestModifier] 初始化失败:", error2);
        throw error2;
      }
    });
  }
  function clearAllRefererRules() {
    return __async(this, null, function* () {
      try {
        const existingRules = yield chrome.declarativeNetRequest.getDynamicRules();
        const ruleIdsToRemove = existingRules.filter((rule) => PLATFORM_REFERER_RULES.some((config2) => config2.ruleId === rule.id)).map((rule) => rule.id);
        if (ruleIdsToRemove.length > 0) {
          yield chrome.declarativeNetRequest.updateDynamicRules({
            removeRuleIds: ruleIdsToRemove
          });
          console.log("[BackgroundRequestModifier] 已清除现有规则:", ruleIdsToRemove.length);
        }
      } catch (error2) {
        console.error("[BackgroundRequestModifier] 清除规则失败:", error2);
      }
    });
  }
  const DB_NAME$1 = "mcp_execution_logs";
  const DB_VERSION$1 = 1;
  const LOG_STORE = "logs";
  const MAX_LOGS = 5e3;
  const RETENTION_DAYS = 7;
  const BATCH_SIZE = 50;
  const BATCH_TIMEOUT = 5e3;
  const MAX_QUEUE_SIZE = 1e3;
  class MCPExecutionLogger {
    constructor() {
      __publicField2(this, "db", null);
      __publicField2(this, "isInitialized", false);
      __publicField2(this, "initializationPromise", null);
      // 批量写入队列
      __publicField2(this, "logQueue", []);
      __publicField2(this, "batchTimer", null);
      __publicField2(this, "isFlushingBatch", false);
    }
    /**
     * 初始化数据库（使用Promise缓存避免重复初始化）
     */
    initialize() {
      return __async(this, null, function* () {
        if (this.isInitialized) return;
        if (this.initializationPromise) {
          return this.initializationPromise;
        }
        this.initializationPromise = new Promise((resolve2, reject) => {
          if (!indexedDB) {
            const error2 = new Error("IndexedDB not supported");
            console.error("[MCP Logger] IndexedDB 不支持:", error2);
            this.initializationPromise = null;
            reject(error2);
            return;
          }
          const request = indexedDB.open(DB_NAME$1, DB_VERSION$1);
          request.onerror = () => {
            console.error("[MCP Logger] 数据库打开失败:", request.error);
            this.initializationPromise = null;
            reject(request.error);
          };
          request.onsuccess = () => {
            this.db = request.result;
            this.isInitialized = true;
            resolve2();
          };
          request.onupgradeneeded = (event) => {
            console.log(
              "[MCP Logger] 数据库需要升级，当前版本:",
              event.oldVersion,
              "目标版本:",
              event.newVersion
            );
            const db = event.target.result;
            if (!db.objectStoreNames.contains(LOG_STORE)) {
              const logStore = db.createObjectStore(LOG_STORE, { keyPath: "id" });
              logStore.createIndex("timestamp", "timestamp", { unique: false });
              logStore.createIndex("toolName", "toolName", { unique: false });
              logStore.createIndex("status", "status", { unique: false });
              logStore.createIndex("toolStatus", ["toolName", "status"], { unique: false });
            }
          };
        });
        return this.initializationPromise;
      });
    }
    /**
     * 生成日志ID
     */
    generateLogId() {
      return `log_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    }
    /**
     * 数据清理（移除敏感信息，限制大小）
     */
    sanitizeData(data) {
      if (!data) return data;
      try {
        const dataStr = JSON.stringify(data);
        if (dataStr.length > 1e4) {
          return {
            _truncated: true,
            _originalSize: dataStr.length,
            _preview: dataStr.substring(0, 500) + "..."
          };
        }
        return data;
      } catch (error2) {
        return { _error: "Failed to serialize data" };
      }
    }
    /**
     * 批量写入日志到数据库
     */
    flushBatch() {
      return __async(this, null, function* () {
        if (this.isFlushingBatch || this.logQueue.length === 0) {
          return;
        }
        this.isFlushingBatch = true;
        const logsToWrite = [...this.logQueue];
        this.logQueue = [];
        if (this.batchTimer) {
          clearTimeout(this.batchTimer);
          this.batchTimer = null;
        }
        try {
          yield this.initialize();
          if (!this.db) {
            throw new Error("Database not initialized");
          }
          const transaction = this.db.transaction([LOG_STORE], "readwrite");
          const store = transaction.objectStore(LOG_STORE);
          const addPromises = logsToWrite.map((log) => {
            return new Promise((resolve2, reject) => {
              const request = store.add(log);
              request.onsuccess = () => resolve2();
              request.onerror = () => reject(request.error);
            });
          });
          yield Promise.all(addPromises);
          this.cleanupIfNeeded().catch(console.warn);
        } catch (error2) {
          console.error("[MCP Logger] 批量写入失败:", error2);
          this.logQueue.unshift(...logsToWrite);
        } finally {
          this.isFlushingBatch = false;
        }
      });
    }
    /**
     * 启动批量写入定时器
     */
    scheduleBatchFlush() {
      if (this.batchTimer) {
        return;
      }
      this.batchTimer = setTimeout(() => {
        this.flushBatch().catch(console.warn);
      }, BATCH_TIMEOUT);
    }
    /**
     * 记录工具执行（使用批量写入机制）
     */
    logExecution(toolName, input, result2, metadata2) {
      return __async(this, null, function* () {
        const logId = this.generateLogId();
        const log = {
          id: logId,
          timestamp: Date.now(),
          toolName,
          input: this.sanitizeData(input),
          output: this.sanitizeData(result2.output),
          duration: result2.duration,
          status: result2.error ? "error" : "success",
          error: result2.error,
          metadata: metadata2
        };
        if (this.logQueue.length >= MAX_QUEUE_SIZE) {
          console.warn("[MCP Logger] 队列已满，强制执行批量写入");
          yield this.flushBatch();
        }
        this.logQueue.push(log);
        if (this.logQueue.length >= BATCH_SIZE) {
          this.flushBatch().catch(console.warn);
        } else {
          this.scheduleBatchFlush();
        }
        return logId;
      });
    }
    /**
     * 查询日志
     */
    queryLogs() {
      return __async(this, arguments, function* (options = {}) {
        yield this.initialize();
        return new Promise((resolve2, reject) => {
          const transaction = this.db.transaction([LOG_STORE], "readonly");
          const store = transaction.objectStore(LOG_STORE);
          let index2;
          let range;
          if (options.toolName && options.status) {
            index2 = store.index("toolStatus");
            range = IDBKeyRange.only([options.toolName, options.status]);
          } else if (options.toolName) {
            index2 = store.index("toolName");
            range = IDBKeyRange.only(options.toolName);
          } else if (options.status) {
            index2 = store.index("status");
            range = IDBKeyRange.only(options.status);
          } else {
            index2 = store.index("timestamp");
            if (options.startTime && options.endTime) {
              range = IDBKeyRange.bound(options.startTime, options.endTime);
            } else if (options.startTime) {
              range = IDBKeyRange.lowerBound(options.startTime);
            } else if (options.endTime) {
              range = IDBKeyRange.upperBound(options.endTime);
            }
          }
          const logs = [];
          let skipped = 0;
          let collected = 0;
          const request = index2.openCursor(range, "prev");
          request.onsuccess = (event) => {
            const cursor = event.target.result;
            if (cursor && (!options.limit || collected < options.limit)) {
              const log = cursor.value;
              let matches = true;
              if (options.startTime && log.timestamp < options.startTime) matches = false;
              if (options.endTime && log.timestamp > options.endTime) matches = false;
              if (matches) {
                if (options.offset && skipped < options.offset) {
                  skipped++;
                } else {
                  logs.push(log);
                  collected++;
                }
              }
              cursor.continue();
            } else {
              resolve2(logs);
            }
          };
          request.onerror = () => reject(request.error);
        });
      });
    }
    /**
     * 获取统计信息
     */
    getStats() {
      return __async(this, null, function* () {
        yield this.initialize();
        return new Promise((resolve2, reject) => {
          const transaction = this.db.transaction([LOG_STORE], "readonly");
          const store = transaction.objectStore(LOG_STORE);
          const stats = {
            totalLogs: 0,
            dbSize: 0,
            avgDuration: 0,
            logsByStatus: {},
            logsByTool: {},
            recentErrors: []
          };
          let totalDuration = 0;
          const countRequest = store.count();
          countRequest.onsuccess = () => {
            stats.totalLogs = countRequest.result;
            if (stats.totalLogs === 0) {
              resolve2(stats);
              return;
            }
            const cursor = store.openCursor();
            cursor.onsuccess = (event) => {
              const cursor2 = event.target.result;
              if (cursor2) {
                const log = cursor2.value;
                if (!stats.oldestLog || log.timestamp < stats.oldestLog) {
                  stats.oldestLog = log.timestamp;
                }
                if (!stats.newestLog || log.timestamp > stats.newestLog) {
                  stats.newestLog = log.timestamp;
                }
                stats.logsByStatus[log.status] = (stats.logsByStatus[log.status] || 0) + 1;
                stats.logsByTool[log.toolName] = (stats.logsByTool[log.toolName] || 0) + 1;
                totalDuration += log.duration;
                if (log.status === "error" && stats.recentErrors.length < 10) {
                  stats.recentErrors.push(log);
                }
                cursor2.continue();
              } else {
                stats.avgDuration = stats.totalLogs > 0 ? totalDuration / stats.totalLogs : 0;
                stats.recentErrors.sort((a, b) => b.timestamp - a.timestamp);
                resolve2(stats);
              }
            };
          };
          countRequest.onerror = () => reject(countRequest.error);
        });
      });
    }
    /**
     * 检查并执行清理
     */
    cleanupIfNeeded() {
      return __async(this, null, function* () {
        try {
          const stats = yield this.getStats();
          const needsCleanup = stats.totalLogs > MAX_LOGS || stats.oldestLog && Date.now() - stats.oldestLog > RETENTION_DAYS * 24 * 60 * 60 * 1e3;
          if (needsCleanup) {
            yield this.cleanup();
          }
        } catch (error2) {
          console.warn("[MCP Logger] 自动清理检查失败:", error2);
        }
      });
    }
    /**
     * 清理旧日志
     */
    cleanup() {
      return __async(this, null, function* () {
        yield this.initialize();
        const cutoffTime = Date.now() - RETENTION_DAYS * 24 * 60 * 60 * 1e3;
        return new Promise((resolve2, reject) => {
          const transaction = this.db.transaction([LOG_STORE], "readwrite");
          const store = transaction.objectStore(LOG_STORE);
          let deletedLogs = 0;
          const timeIndex = store.index("timestamp");
          const timeRange = IDBKeyRange.upperBound(cutoffTime);
          const timeRequest = timeIndex.openCursor(timeRange);
          timeRequest.onsuccess = (event) => {
            const cursor = event.target.result;
            if (cursor) {
              cursor.delete();
              deletedLogs++;
              cursor.continue();
            } else {
              this.cleanupByCount(MAX_LOGS - deletedLogs).then((countDeleted) => {
                const totalDeleted = deletedLogs + countDeleted;
                if (totalDeleted > 0) {
                  console.log(`[MCP Logger] 清理完成: 删除 ${totalDeleted} 条日志`);
                }
                resolve2({ deletedLogs: totalDeleted });
              }).catch(reject);
            }
          };
          timeRequest.onerror = () => reject(timeRequest.error);
        });
      });
    }
    /**
     * 按数量清理（保留最新的N条）
     */
    cleanupByCount(keepCount) {
      return __async(this, null, function* () {
        return new Promise((resolve2, reject) => {
          const transaction = this.db.transaction([LOG_STORE], "readwrite");
          const store = transaction.objectStore(LOG_STORE);
          const countRequest = store.count();
          countRequest.onsuccess = () => {
            const totalCount = countRequest.result;
            if (totalCount <= keepCount) {
              resolve2(0);
              return;
            }
            const deleteCount = totalCount - keepCount;
            let deleted = 0;
            const index2 = store.index("timestamp");
            const cursor = index2.openCursor();
            cursor.onsuccess = (event) => {
              const cursor2 = event.target.result;
              if (cursor2 && deleted < deleteCount) {
                cursor2.delete();
                deleted++;
                cursor2.continue();
              } else {
                resolve2(deleted);
              }
            };
          };
          countRequest.onerror = () => reject(countRequest.error);
        });
      });
    }
    /**
     * 清空所有数据
     */
    clearAll() {
      return __async(this, null, function* () {
        yield this.initialize();
        return new Promise((resolve2, reject) => {
          const transaction = this.db.transaction([LOG_STORE], "readwrite");
          const store = transaction.objectStore(LOG_STORE);
          const request = store.clear();
          request.onsuccess = () => {
            console.log("[MCP Logger] 所有数据已清空");
            resolve2();
          };
          request.onerror = () => reject(request.error);
        });
      });
    }
    /**
     * 销毁日志记录器，确保剩余日志被写入
     */
    destroy() {
      return __async(this, null, function* () {
        console.log("[MCP Logger] 正在销毁日志记录器...");
        if (this.batchTimer) {
          clearTimeout(this.batchTimer);
          this.batchTimer = null;
        }
        if (this.logQueue.length > 0) {
          yield this.flushBatch();
        }
        if (this.db) {
          this.db.close();
          this.db = null;
        }
        this.isInitialized = false;
        this.initializationPromise = null;
      });
    }
  }
  let mcpLogger = null;
  function getMCPExecutionLogger() {
    if (!mcpLogger) {
      mcpLogger = new MCPExecutionLogger();
    }
    return mcpLogger;
  }
  function handleAsyncMessage(handler, sendResponse, timeout = 3e4) {
    let timeoutId = null;
    let isCompleted = false;
    timeoutId = setTimeout(() => {
      if (!isCompleted) {
        isCompleted = true;
        console.error("[AsyncMessageHandler] 请求超时");
        sendResponse({
          success: false,
          error: "请求超时",
          timeout: true
        });
      }
    }, timeout);
    handler().then((result2) => {
      if (!isCompleted) {
        isCompleted = true;
        if (timeoutId) clearTimeout(timeoutId);
        sendResponse(__spreadValues({
          success: true
        }, result2));
      }
    }).catch((error2) => {
      if (!isCompleted) {
        isCompleted = true;
        if (timeoutId) clearTimeout(timeoutId);
        console.error("[AsyncMessageHandler] 处理失败:", error2);
        sendResponse({
          success: false,
          error: error2 instanceof Error ? error2.message : String(error2)
        });
      }
    });
    return true;
  }
  function handleGetStorageStats() {
    return __async(this, null, function* () {
      try {
        const { getGlobalContentIndexer: getGlobalContentIndexer2 } = yield Promise.resolve().then(() => contentIndexer);
        const contentIndexer$1 = getGlobalContentIndexer2();
        const stats = contentIndexer$1.getStats();
        return {
          success: true,
          stats: {
            indexedPages: stats.indexedPages || 0,
            totalDocuments: stats.totalDocuments || 0,
            totalTabs: stats.totalTabs || 0,
            indexSize: stats.indexSize || 0,
            isInitialized: stats.isInitialized || false,
            semanticEngineReady: stats.semanticEngineReady || false,
            semanticEngineInitializing: stats.semanticEngineInitializing || false
          }
        };
      } catch (error2) {
        console.error("Background: Failed to get storage stats:", error2);
        return {
          success: false,
          error: error2.message,
          stats: {
            indexedPages: 0,
            totalDocuments: 0,
            totalTabs: 0,
            indexSize: 0,
            isInitialized: false,
            semanticEngineReady: false,
            semanticEngineInitializing: false
          }
        };
      }
    });
  }
  function handleClearAllData() {
    return __async(this, null, function* () {
      try {
        try {
          const { getGlobalContentIndexer: getGlobalContentIndexer2 } = yield Promise.resolve().then(() => contentIndexer);
          const contentIndexer$1 = getGlobalContentIndexer2();
          yield contentIndexer$1.clearAllIndexes();
          console.log("Storage: ContentIndexer indexes cleared successfully");
        } catch (indexerError) {
          console.warn("Background: Failed to clear ContentIndexer indexes:", indexerError);
        }
        try {
          const { clearAllVectorData: clearAllVectorData2 } = yield Promise.resolve().then(() => vectorDatabase);
          yield clearAllVectorData2();
          console.log("Storage: Vector database data cleared successfully");
        } catch (vectorError) {
          console.warn("Background: Failed to clear vector data:", vectorError);
        }
        try {
          const keysToRemove = ["vectorDatabaseStats", "lastCleanupTime", "contentIndexerStats"];
          yield chrome.storage.local.remove(keysToRemove);
          console.log("Storage: Chrome storage data cleared successfully");
        } catch (storageError) {
          console.warn("Background: Failed to clear chrome storage data:", storageError);
        }
        return { success: true };
      } catch (error2) {
        console.error("Background: Failed to clear all data:", error2);
        return { success: false, error: error2.message };
      }
    });
  }
  function handleGetMCPLogStats() {
    return __async(this, null, function* () {
      try {
        const logger2 = getMCPExecutionLogger();
        const stats = yield logger2.getStats();
        return {
          success: true,
          stats
        };
      } catch (error2) {
        console.error("Background: Failed to get MCP log stats:", error2);
        return {
          success: false,
          error: error2.message
        };
      }
    });
  }
  function handleQueryMCPLogs(options) {
    return __async(this, null, function* () {
      try {
        const logger2 = getMCPExecutionLogger();
        const logs = yield logger2.queryLogs(options);
        return {
          success: true,
          logs
        };
      } catch (error2) {
        console.error("Background: Failed to query MCP logs:", error2);
        return {
          success: false,
          error: error2.message
        };
      }
    });
  }
  function handleClearMCPLogs() {
    return __async(this, null, function* () {
      try {
        const logger2 = getMCPExecutionLogger();
        yield logger2.clearAll();
        return {
          success: true
        };
      } catch (error2) {
        console.error("Background: Failed to clear MCP logs:", error2);
        return {
          success: false,
          error: error2.message
        };
      }
    });
  }
  function handleCleanupMCPLogs() {
    return __async(this, null, function* () {
      try {
        const logger2 = getMCPExecutionLogger();
        const result2 = yield logger2.cleanup();
        return {
          success: true,
          deletedLogs: result2.deletedLogs
        };
      } catch (error2) {
        console.error("Background: Failed to cleanup MCP logs:", error2);
        return {
          success: false,
          error: error2.message
        };
      }
    });
  }
  const initStorageManagerListener = () => {
    chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
      switch (message.type) {
        case BACKGROUND_MESSAGE_TYPES$1.GET_STORAGE_STATS:
          return handleAsyncMessage(() => handleGetStorageStats(), sendResponse);
        case BACKGROUND_MESSAGE_TYPES$1.CLEAR_ALL_DATA:
          return handleAsyncMessage(() => handleClearAllData(), sendResponse);
        case BACKGROUND_MESSAGE_TYPES$1.GET_MCP_LOG_STATS:
          return handleAsyncMessage(() => handleGetMCPLogStats(), sendResponse);
        case BACKGROUND_MESSAGE_TYPES$1.QUERY_MCP_LOGS:
          return handleAsyncMessage(() => handleQueryMCPLogs(message.options || {}), sendResponse);
        case BACKGROUND_MESSAGE_TYPES$1.CLEAR_MCP_LOGS:
          return handleAsyncMessage(() => handleClearMCPLogs(), sendResponse);
        case BACKGROUND_MESSAGE_TYPES$1.CLEANUP_MCP_LOGS:
          return handleAsyncMessage(() => handleCleanupMCPLogs(), sendResponse);
        default:
          return false;
      }
    });
  };
  function sendEmptySniffResult(url2) {
    browser$1.runtime.sendMessage({
      type: "SNIFF_RESULT",
      data: {
        url: url2,
        title: "",
        timestamp: Date.now(),
        resources: []
      }
    }).catch((error2) => {
      console.debug("发送空嗅探结果失败(可能是没有监听器):", error2);
    });
  }
  function injectSniffScript(tabId, url2) {
    return __async(this, null, function* () {
      if (!url2) {
        sendEmptySniffResult("");
        return;
      }
      const excludedProtocols = ["chrome:", "edge:", "about:", "chrome-extension:", "edge-extension:"];
      if (excludedProtocols.some((protocol) => url2.startsWith(protocol))) {
        console.log("🚫 页面不支持嗅探,重置嗅探数量:", url2);
        sendEmptySniffResult(url2);
        return;
      }
      try {
        yield browser$1.scripting.executeScript({
          target: { tabId },
          files: ["/sniff.js"]
        });
      } catch (error2) {
        console.error(`❌ Failed to inject sniff script into tab ${tabId}:`, error2);
        sendEmptySniffResult(url2);
      }
    });
  }
  const recentTabsHistory = [];
  const MAX_RECENT_TABS = 10;
  function addToRecentTabs(tabInfo) {
    const existingIndex = recentTabsHistory.findIndex((t) => t.id === tabInfo.id);
    if (existingIndex !== -1) {
      recentTabsHistory.splice(existingIndex, 1);
    }
    recentTabsHistory.unshift(tabInfo);
    if (recentTabsHistory.length > MAX_RECENT_TABS) {
      recentTabsHistory.pop();
    }
    browser$1.runtime.sendMessage({
      type: "recent_tabs_update",
      tabs: recentTabsHistory.slice(0, 3)
      // 只发送前 3 个
    });
  }
  function getCurrentTab(tabId, shouldInjectSniff = true) {
    browser$1.tabs.get(tabId).then((tab) => __async(null, null, function* () {
      const tabInfo = {
        id: tab.id,
        title: tab.title,
        url: tab.url,
        windowId: tab.windowId,
        favIconBase64: "",
        lastAccessTime: Date.now(),
        status: tab.status
      };
      browser$1.runtime.sendMessage({
        type: "current_tab",
        tab: tabInfo
      });
      if (tab.favIconUrl) {
        const base642 = yield fetchImageAsBase64(tab.favIconUrl);
        const completeTabInfo = {
          id: tab.id,
          title: tab.title || "",
          url: tab.url || "",
          windowId: tab.windowId,
          favIconBase64: base642.data || "",
          lastAccessTime: Date.now(),
          status: tab.status
        };
        browser$1.runtime.sendMessage({
          type: "current_tab",
          tab: completeTabInfo
        });
        addToRecentTabs(completeTabInfo);
      }
      if (shouldInjectSniff) {
        injectSniffScript(tabId, tab.url);
      }
    }));
  }
  function initTabSwitchListener() {
    browser$1.tabs.onActivated.addListener((activeInfo) => {
      getCurrentTab(activeInfo.tabId);
    });
    browser$1.tabs.onUpdated.addListener((tabId, changeInfo, tab) => __async(null, null, function* () {
      const activeTabs = yield browser$1.tabs.query({ active: true, currentWindow: true });
      if (activeTabs.length === 0 || activeTabs[0].id !== tabId) {
        return;
      }
      if (changeInfo.status === "loading") {
        browser$1.runtime.sendMessage({
          type: "current_tab",
          tab: {
            id: tabId,
            status: "loading"
          }
        });
      } else if (changeInfo.status === "complete") {
        browser$1.runtime.sendMessage({
          type: "current_tab",
          tab: {
            id: tabId,
            status: "complete"
          }
        });
        setTimeout(() => {
          getCurrentTab(tabId, false);
        }, 100);
        setTimeout(() => {
          injectSniffScript(tabId, tab.url);
        }, 500);
      } else if (changeInfo.title || changeInfo.url) {
        getCurrentTab(tabId, false);
      }
    }));
    browser$1.tabs.onRemoved.addListener((tabId) => {
      const removedIndex = recentTabsHistory.findIndex((t) => t.id === tabId);
      if (removedIndex !== -1) {
        recentTabsHistory.splice(removedIndex, 1);
        browser$1.runtime.sendMessage({
          type: "recent_tabs_update",
          tabs: recentTabsHistory.slice(0, 3)
        });
      }
    });
    browser$1.runtime.onMessage.addListener((message) => {
      if (message.type === "get_current_tab") {
        browser$1.tabs.query({ active: true, currentWindow: true }).then((tabs) => {
          getCurrentTab(tabs[0].id);
        });
      }
      if (message.type === "get_recent_tabs") {
        const limit2 = message.limit || 3;
        browser$1.runtime.sendMessage({
          type: "recent_tabs_update",
          tabs: recentTabsHistory.slice(0, limit2)
        });
      }
    });
  }
  class ChatAgentHandler {
    constructor() {
      __publicField2(this, "sessions", /* @__PURE__ */ new Map());
    }
    /**
     * 发送流式聊天请求
     */
    sendMessage(params, port) {
      return __async(this, null, function* () {
        var _b2, _c2;
        if (this.sessions.size > 10) {
          console.error(`Background: Sessions Map 异常增长 (${this.sessions.size})，可能存在泄漏`);
          const now = Date.now();
          const FIVE_MINUTES = 5 * 60 * 1e3;
          this.sessions.forEach((session2, p) => {
            if (now - session2.createdAt > FIVE_MINUTES) {
              console.warn("Background: 清理超时 session");
              session2.abortController.abort();
              this.sessions.delete(p);
            }
          });
        }
        const existingSession = this.sessions.get(port);
        if (existingSession) {
          console.warn("Background: Port 已有进行中的请求，中止旧请求");
          existingSession.abortController.abort();
          this.sessions.delete(port);
        }
        const session = {
          abortController: new AbortController(),
          receivedMessageStop: false,
          createdAt: Date.now()
        };
        this.sessions.set(port, session);
        try {
          const _a3 = params, { chatId } = _a3, others = __objRest(_a3, ["chatId"]);
          const API_BASE_URL = yield getApiBaseUrl$1("v1");
          const commonHeaders = yield getCommonHeaders();
          const deviceStorage = yield chrome.storage.local.get("device_config");
          console.error("Background: 设备信息:", deviceStorage);
          const deviceId = (_b2 = deviceStorage.device_config) == null ? void 0 : _b2.deviceId;
          const _headers = __spreadValues({
            "Content-Type": "application/json"
          }, commonHeaders);
          let threadId = chatId;
          if (!chatId) {
            const seesion = yield fetch(`${API_BASE_URL}/v1/sessions`, {
              method: "POST",
              headers: __spreadValues({}, _headers),
              body: JSON.stringify({
                auto_start: true
              })
            }).then((response2) => response2.json());
            if (!seesion.id) {
              throw new Error(`HTTP ${seesion.status}: ${seesion.statusText}`);
            }
            threadId = seesion.id;
          }
          const requestBody = __spreadValues({
            // thread_id: threadId,
            device_id: deviceId
          }, others);
          console.log("Background: 发送流式聊天请求:", requestBody);
          this.sendToPort(port, { type: "stream_start", payload: { threadId } });
          const response = yield fetch(`${API_BASE_URL}/v1/sessions/${threadId}/chat`, {
            method: "POST",
            headers: __spreadValues({
              Accept: "text/event-stream",
              "Cache-Control": "no-cache"
            }, _headers),
            body: JSON.stringify(requestBody),
            signal: session.abortController.signal
          });
          if (!response.ok) {
            let errorMessage = `HTTP ${response.status}: ${response.statusText}`;
            try {
              const errorData = yield response.json();
              errorMessage = ((_c2 = errorData.error) == null ? void 0 : _c2.message) || // 格式1: { error: { message: "xxx" } }
              errorData.error || // 格式2: { error: "xxx" }
              errorData.message || // 格式3: { message: "xxx" }
              errorMessage;
            } catch (parseError) {
              try {
                const errorText = yield response.text();
                if (errorText) {
                  errorMessage = errorText;
                }
              } catch (e) {
              }
            }
            throw new Error(errorMessage);
          }
          if (!response.body) {
            throw new Error("响应体为空");
          }
          if (chatId) {
            const { getSessionManager: getSessionManager2 } = yield Promise.resolve().then(() => index$2);
            yield getSessionManager2().trackSession(chatId, {
              toolName: "sidepanel_chat"
            });
          }
          yield this.processStreamResponse(response.body, port);
        } catch (error2) {
          if (error2 instanceof Error && error2.name === "AbortError") {
            console.log("Background: 流式请求被中止");
            this.sendToPort(port, { type: "stream_aborted" });
            return;
          }
          console.error("Background: 流式聊天请求失败:", error2);
          this.sendToPort(port, {
            type: "error",
            error: {
              type: "api_error",
              message: error2 instanceof Error ? error2.message : "未知错误"
            }
          });
        } finally {
          this.sessions.delete(port);
        }
      });
    }
    /**
     * 处理流式响应
     */
    processStreamResponse(body, port) {
      return __async(this, null, function* () {
        const reader = body.getReader();
        const decoder = new TextDecoder();
        let buffer2 = "";
        const session = this.sessions.get(port);
        if (!session) {
          console.error("Background: Session 不存在");
          return;
        }
        session.receivedMessageStop = false;
        try {
          while (true) {
            const { done, value } = yield reader.read();
            if (done) {
              console.log("Background: 流式响应结束");
              if (!session.receivedMessageStop) {
                console.warn("Background: 检测到异常断开（未收到 message_stop），发送兜底事件");
                this.sendToPort(port, {
                  type: "stream_event",
                  event: { type: "message_stop" }
                });
              }
              break;
            }
            buffer2 += decoder.decode(value, { stream: true });
            buffer2 = this.processBufferedEvents(buffer2, port);
          }
          if (buffer2.trim()) {
            this.processBufferedEvents(buffer2 + "\n\n", port);
          }
        } catch (error2) {
          console.error("Background: 处理流式响应时出错:", error2);
          this.sendToPort(port, {
            type: "error",
            error: {
              type: "stream_error",
              message: error2 instanceof Error ? error2.message : "流式响应处理失败"
            }
          });
        } finally {
          reader.releaseLock();
        }
      });
    }
    /**
     * 处理缓冲区中的事件
     */
    processBufferedEvents(buffer2, port) {
      const events = buffer2.split("\n\n");
      const remainingBuffer = events.pop() || "";
      const session = this.sessions.get(port);
      if (!session) {
        console.error("Background: Session 不存在");
        return remainingBuffer;
      }
      for (const eventData of events) {
        if (!eventData.trim()) continue;
        try {
          const event = this.parseSSEEvent(eventData);
          if (event) {
            if (event.type === "message_stop") {
              session.receivedMessageStop = true;
            }
            this.sendToPort(port, { type: "stream_event", event });
          }
        } catch (error2) {
          console.error("Background: 解析事件失败:", error2, "原始数据:", eventData);
          this.sendToPort(port, {
            type: "error",
            error: {
              type: "parse_error",
              message: error2 instanceof Error ? error2.message : "事件解析失败"
            }
          });
        }
      }
      return remainingBuffer;
    }
    /**
     * 解析 Server-Sent Events 格式的事件
     */
    parseSSEEvent(eventData) {
      const lines = eventData.trim().split("\n");
      let eventType = "";
      let data = "";
      for (const line of lines) {
        if (line.startsWith("event:")) {
          eventType = line.substring(6).trim();
        } else if (line.startsWith("data:")) {
          data = line.substring(5).trim();
        }
      }
      if (!data) {
        return null;
      }
      try {
        const parsedData = JSON.parse(data);
        if (eventType && parsedData.type !== eventType) {
          console.warn(
            `Background: 事件类型不匹配: header=${eventType}, data.type=${parsedData.type}`
          );
        }
        return parsedData;
      } catch (error2) {
        console.error("Background: JSON 解析失败:", error2, "数据:", data);
        throw new Error(`JSON 解析失败: ${error2}`);
      }
    }
    /**
     * 向 port 发送消息
     */
    sendToPort(port, response) {
      try {
        port.postMessage(response);
      } catch (error2) {
        console.error("Background: 发送消息到 port 失败:", error2);
      }
    }
    /**
     * 取消指定 port 的流式请求
     */
    abort(port) {
      const session = this.sessions.get(port);
      if (session) {
        session.abortController.abort();
        this.sessions.delete(port);
        console.log("Background: 流式请求已取消");
      }
    }
    /**
     * 重连到进行中会话的 SSE 流
     * 用于历史会话切换时恢复实时流
     */
    reconnectStream(sessionId, port) {
      return __async(this, null, function* () {
        var _a3;
        if (this.sessions.size > 10) {
          console.error(`Background: Sessions Map 异常增长 (${this.sessions.size})，可能存在泄漏`);
          const now = Date.now();
          const FIVE_MINUTES = 5 * 60 * 1e3;
          this.sessions.forEach((session2, p) => {
            if (now - session2.createdAt > FIVE_MINUTES) {
              console.warn("Background: 清理超时 session");
              session2.abortController.abort();
              this.sessions.delete(p);
            }
          });
        }
        const existingSession = this.sessions.get(port);
        if (existingSession) {
          console.warn("Background: Port 已有进行中的请求，中止旧请求");
          existingSession.abortController.abort();
          this.sessions.delete(port);
        }
        const session = {
          abortController: new AbortController(),
          receivedMessageStop: false,
          createdAt: Date.now()
        };
        this.sessions.set(port, session);
        try {
          const API_BASE_URL = yield getApiBaseUrl$1("v1");
          const commonHeaders = yield getCommonHeaders();
          const headers = __spreadValues({
            "Content-Type": "application/json",
            Accept: "text/event-stream",
            "Cache-Control": "no-cache"
          }, commonHeaders);
          console.log(`Background: 重连 SSE 流，sessionId: ${sessionId}`);
          this.sendToPort(port, { type: "stream_start", payload: { threadId: sessionId } });
          const response = yield fetch(`${API_BASE_URL}/v1/sessions/${sessionId}/stream`, {
            method: "GET",
            headers,
            signal: session.abortController.signal
          });
          if (!response.ok) {
            let errorMessage = `HTTP ${response.status}: ${response.statusText}`;
            try {
              const errorData = yield response.json();
              errorMessage = ((_a3 = errorData.error) == null ? void 0 : _a3.message) || errorData.error || errorData.message || errorMessage;
            } catch (e) {
            }
            throw new Error(errorMessage);
          }
          if (!response.body) {
            throw new Error("响应体为空");
          }
          yield this.processStreamResponse(response.body, port);
        } catch (error2) {
          if (error2 instanceof Error && error2.name === "AbortError") {
            console.log("Background: SSE 重连请求被中止");
            this.sendToPort(port, { type: "stream_aborted" });
            return;
          }
          console.error("Background: SSE 重连请求失败:", error2);
          this.sendToPort(port, {
            type: "error",
            error: {
              type: "reconnect_error",
              message: error2 instanceof Error ? error2.message : "重连失败"
            }
          });
        } finally {
          this.sessions.delete(port);
        }
      });
    }
    /**
     * 清理所有会话（扩展重载时调用）
     */
    cleanupAll() {
      console.log(`Background: 清理所有会话，当前会话数: ${this.sessions.size}`);
      this.sessions.forEach((session) => {
        session.abortController.abort();
      });
      this.sessions.clear();
    }
    /**
     * 获取当前会话数量（用于调试）
     */
    getSessionCount() {
      return this.sessions.size;
    }
  }
  const chatAgentHandler = new ChatAgentHandler();
  function initChatAgentListener() {
    chrome.runtime.onConnect.addListener((port) => {
      if (port.name !== "chat-agent") {
        return;
      }
      console.log("Background: Chat agent port 连接");
      port.onMessage.addListener((message) => {
        console.log("Background: 接收到 chat agent 消息:", message);
        switch (message.type) {
          case "send_message":
            chatAgentHandler.sendMessage(message.params, port);
            break;
          case "abort":
            chatAgentHandler.abort(port);
            break;
          case "reconnect_stream":
            chatAgentHandler.reconnectStream(message.sessionId, port);
            break;
          default:
            console.warn("Background: 未知的消息类型:", message);
        }
      });
      port.onDisconnect.addListener(() => {
        console.log("Background: Chat agent port 断开连接");
        chatAgentHandler.abort(port);
      });
    });
    console.log("Background: Chat agent 监听器已初始化");
  }
  function cleanupChatAgent() {
    chatAgentHandler.cleanupAll();
  }
  class CapturedRequestsDB {
    constructor() {
      __publicField2(this, "requests", []);
      __publicField2(this, "nextId", 1);
      __publicField2(this, "MAX_REQUESTS", 1e3);
    }
    // 最大存储数量
    /**
     * 根据标签页 ID 删除所有请求
     */
    deleteByTabId(tabId) {
      return __async(this, null, function* () {
        const before = this.requests.length;
        this.requests = this.requests.filter((r) => r.tabId !== tabId);
        const deleted = before - this.requests.length;
        console.log(`[CapturedRequestsDB] 删除标签页 ${tabId} 的 ${deleted} 条请求`);
        return deleted;
      });
    }
    /**
     * 获取按 Host 分组的请求
     * @param options 查询选项
     */
    getGroupedRequests(options) {
      return __async(this, null, function* () {
        let sorted = [...this.requests].sort((a, b) => b.timestamp - a.timestamp);
        if (options == null ? void 0 : options.offset) {
          sorted = sorted.slice(options.offset);
        }
        if (options == null ? void 0 : options.limit) {
          sorted = sorted.slice(0, options.limit);
        }
        const grouped = sorted.reduce(
          (acc, req) => {
            if (!acc[req.host]) {
              acc[req.host] = [];
            }
            acc[req.host].push(req);
            return acc;
          },
          {}
        );
        return Object.entries(grouped).map(([host, requests]) => ({
          host,
          requests,
          count: requests.length
        })).sort((a, b) => {
          const aLatest = Math.max(...a.requests.map((r) => r.timestamp));
          const bLatest = Math.max(...b.requests.map((r) => r.timestamp));
          return bLatest - aLatest;
        });
      });
    }
    /**
     * 获取按 Host 分组的请求（使用 liveQuery 实现实时更新）
     * 注意：内存版本不支持真正的 liveQuery，直接返回当前数据
     */
    getGroupedRequestsLive() {
      return __async(this, null, function* () {
        return {
          subscribe: (callback) => {
            this.getGroupedRequests().then(callback);
            return { unsubscribe: () => {
            } };
          }
        };
      });
    }
    /**
     * 获取指定 Host 的所有请求
     */
    getRequestsByHost(host) {
      return __async(this, null, function* () {
        return this.requests.filter((r) => r.host === host).sort((a, b) => b.timestamp - a.timestamp);
      });
    }
    /**
     * 获取指定标签页的所有请求
     */
    getRequestsByTabId(tabId) {
      return __async(this, null, function* () {
        return this.requests.filter((r) => r.tabId === tabId).sort((a, b) => b.timestamp - a.timestamp);
      });
    }
    /**
     * 清空所有请求
     */
    clearAllRequests() {
      return __async(this, null, function* () {
        const count = this.requests.length;
        this.requests = [];
        this.nextId = 1;
        console.log(`[CapturedRequestsDB] 已清空所有请求，共 ${count} 条`);
      });
    }
    /**
     * 获取数据库统计信息
     */
    getStats() {
      return __async(this, null, function* () {
        if (this.requests.length === 0) {
          return {
            totalRequests: 0,
            totalHosts: 0,
            totalSize: 0,
            oldestTimestamp: 0,
            newestTimestamp: 0
          };
        }
        const hosts = new Set(this.requests.map((r) => r.host));
        const totalSize = this.requests.reduce((sum, r) => sum + r.size, 0);
        const timestamps = this.requests.map((r) => r.timestamp);
        return {
          totalRequests: this.requests.length,
          totalHosts: hosts.size,
          totalSize,
          oldestTimestamp: Math.min(...timestamps),
          newestTimestamp: Math.max(...timestamps)
        };
      });
    }
    /**
     * 清理旧数据（超过指定天数的数据）
     */
    cleanupOldData(daysToKeep = 7) {
      return __async(this, null, function* () {
        const cutoffTime = Date.now() - daysToKeep * 24 * 60 * 60 * 1e3;
        const before = this.requests.length;
        this.requests = this.requests.filter((r) => r.timestamp >= cutoffTime);
        const deleted = before - this.requests.length;
        if (deleted > 0) {
          console.log(`[CapturedRequestsDB] 清理了 ${deleted} 条超过 ${daysToKeep} 天的旧数据`);
        }
        return deleted;
      });
    }
    /**
     * 获取所有成功的请求（状态码 200-299）
     */
    getSuccessfulRequests() {
      return __async(this, null, function* () {
        return this.requests.sort((a, b) => b.timestamp - a.timestamp);
      });
    }
    /**
     * 将请求列表转换为简化的 JSON 格式
     * @param requests 要转换的请求列表
     * @returns 包含 url、timestamp、responseData 的简化对象数组
     */
    formatRequestsToJSON(requests) {
      return requests.map((req) => ({
        url: req.url,
        timestamp: req.timestamp,
        responseData: req.responseBody || ""
      }));
    }
    /**
     * 添加单个请求
     */
    addRequest(request) {
      return __async(this, null, function* () {
        const id2 = this.nextId++;
        const fullRequest = __spreadProps(__spreadValues({}, request), { id: id2 });
        this.requests.push(fullRequest);
        this.logRequest(fullRequest);
        this.enforceMemoryLimit();
        return id2;
      });
    }
    /**
     * 批量添加请求
     */
    addRequests(requests) {
      return __async(this, null, function* () {
        const startId = this.nextId;
        for (const request of requests) {
          yield this.addRequest(request);
        }
        console.log(`[CapturedRequestsDB] 批量添加了 ${requests.length} 条请求`);
        return startId;
      });
    }
    /**
     * 控制台输出请求详情
     */
    logRequest(request) {
      const sizeKB = (request.size / 1024).toFixed(2);
      const timeStr = new Date(request.timestamp).toLocaleTimeString("zh-CN");
      console.groupCollapsed(
        `🌐 [${request.method}] ${request.statusCode} - ${request.host}${request.path} (${sizeKB} KB)`
      );
      console.log("📋 基本信息:");
      console.log("  URL:", request.url);
      console.log("  方法:", request.method);
      console.log("  状态:", request.statusCode);
      console.log("  类型:", request.mimeType);
      console.log("  大小:", `${sizeKB} KB`);
      console.log("  时间:", timeStr);
      console.log("  标签页:", `[${request.tabId}] ${request.tabTitle}`);
      if (request.matchedRules && request.matchedRules.length > 0) {
        console.log("✅ 匹配规则:", request.matchedRules);
      }
      if (request.requestHeaders && Object.keys(request.requestHeaders).length > 0) {
        console.log("📤 请求头:", request.requestHeaders);
      }
      if (request.responseHeaders && Object.keys(request.responseHeaders).length > 0) {
        console.log("📥 响应头:", request.responseHeaders);
      }
      if (request.requestBody) {
        console.log("📤 请求体:", this.formatBody(request.requestBody));
      }
      if (request.responseBody) {
        console.log("📥 响应体:", this.formatBody(request.responseBody, request.base64Encoded));
      }
      console.groupEnd();
    }
    /**
     * 格式化请求/响应体以便在控制台显示
     */
    formatBody(body, isBase64 = false) {
      if (isBase64) {
        return `[Base64 数据，长度: ${typeof body === "string" ? body.length : "未知"}]`;
      }
      if (typeof body === "string" && body.length > 500) {
        return `${body.substring(0, 500)}... [截断，总长度: ${body.length}]`;
      }
      return body;
    }
    /**
     * 强制执行内存限制，删除最旧的请求
     */
    enforceMemoryLimit() {
      if (this.requests.length > this.MAX_REQUESTS) {
        this.requests.sort((a, b) => b.timestamp - a.timestamp);
        const removed = this.requests.splice(this.MAX_REQUESTS);
        console.warn(
          `[CapturedRequestsDB] 内存限制 ${this.MAX_REQUESTS} 条，已删除最旧的 ${removed.length} 条请求`
        );
      }
    }
  }
  const capturedRequestsDB = new CapturedRequestsDB();
  const CAPTURE_RULES = {};
  function fetchCaptureRulesFromAPI() {
    return __async(this, null, function* () {
      try {
        console.log("[CaptureRulesAPI] 开始从接口获取捕获规则...");
        const response = yield apiRequest("/v1/ui-config/request_rule", {
          method: "GET",
          requireAuth: true,
          showErrorToast: false
          // 静默失败，不显示错误提示
        });
        if (!response) {
          console.warn("[CaptureRulesAPI] 接口未返回数据，使用默认配置");
          return CAPTURE_RULES;
        }
        const data = yield response.json();
        if (!(data == null ? void 0 : data.data) || typeof data.data !== "object") {
          console.warn("[CaptureRulesAPI] API 返回的数据格式不正确，使用默认配置");
          console.warn("[CaptureRulesAPI] 期望格式: { data: { [ruleId]: {...} } }");
          return CAPTURE_RULES;
        }
        const rules2 = data.data;
        if (typeof rules2 !== "object" || rules2 === null) {
          console.warn("[CaptureRulesAPI] rules 字段不是有效对象，使用默认配置");
          return CAPTURE_RULES;
        }
        const rulesCount = Object.keys(rules2).length;
        console.log(`[CaptureRulesAPI] 成功从接口获取 ${rulesCount} 条规则`);
        return rules2;
      } catch (error2) {
        console.error("[CaptureRulesAPI] 获取规则失败，使用默认配置:", error2);
        return CAPTURE_RULES;
      }
    });
  }
  const CACHE_CONFIG = {
    storageKey: "capture_rules_cache",
    ttl: 2 * 60 * 60 * 1e3
    // 2小时 TTL
  };
  function isCacheValid(cache) {
    const now = Date.now();
    return now - cache.timestamp < CACHE_CONFIG.ttl;
  }
  function getCacheFromStorage() {
    return __async(this, null, function* () {
      try {
        const result2 = yield chrome.storage.local.get(CACHE_CONFIG.storageKey);
        return result2[CACHE_CONFIG.storageKey] || null;
      } catch (error2) {
        console.error("[CaptureRulesLoader] 读取规则缓存失败:", error2);
        return null;
      }
    });
  }
  function saveCacheToStorage(cache) {
    return __async(this, null, function* () {
      try {
        yield chrome.storage.local.set({ [CACHE_CONFIG.storageKey]: cache });
      } catch (error2) {
        console.error("[CaptureRulesLoader] 保存规则缓存失败:", error2);
      }
    });
  }
  function getCaptureRules() {
    return __async(this, null, function* () {
      try {
        const cache = yield getCacheFromStorage();
        if (cache && isCacheValid(cache)) {
          return cache.rules;
        }
        const rules2 = yield fetchCaptureRulesFromAPI();
        const newCache = {
          rules: rules2,
          timestamp: Date.now()
        };
        yield saveCacheToStorage(newCache);
        return rules2;
      } catch (error2) {
        console.error("[CaptureRulesLoader] 获取规则失败:", error2);
        const cache = yield getCacheFromStorage();
        if (cache) {
          console.warn("[CaptureRulesLoader] 使用过期缓存作为降级方案");
          return cache.rules;
        }
        console.warn("[CaptureRulesLoader] 使用默认规则作为最终降级方案");
        return CAPTURE_RULES;
      }
    });
  }
  function updateCaptureRules() {
    return __async(this, arguments, function* (options = {}) {
      const { forceUpdate = false, respectTTL = false, silent = false } = options;
      try {
        if (respectTTL && !forceUpdate) {
          const cache = yield getCacheFromStorage();
          if (cache && isCacheValid(cache)) {
            return cache.rules;
          }
        }
        const rules2 = yield fetchCaptureRulesFromAPI();
        const newCache = {
          rules: rules2,
          timestamp: Date.now()
        };
        yield saveCacheToStorage(newCache);
        notifyRulesUpdated();
        return rules2;
      } catch (error2) {
        console.error("[CaptureRulesLoader] 更新规则失败:", error2);
        if (!forceUpdate) {
          const cache = yield getCacheFromStorage();
          if (cache) {
            console.warn("[CaptureRulesLoader] 更新失败，使用现有缓存");
            return cache.rules;
          }
        }
        if (silent) {
          console.warn("[CaptureRulesLoader] 静默更新失败，使用默认规则");
          return CAPTURE_RULES;
        }
        throw error2;
      }
    });
  }
  const rulesUpdatedListeners = /* @__PURE__ */ new Set();
  function onRulesUpdated(listener) {
    rulesUpdatedListeners.add(listener);
    return () => {
      rulesUpdatedListeners.delete(listener);
    };
  }
  function notifyRulesUpdated() {
    rulesUpdatedListeners.forEach((listener) => {
      try {
        listener();
      } catch (error2) {
        console.error("[CaptureRulesLoader] 规则更新监听器执行失败:", error2);
      }
    });
  }
  function matchDomain(url2, domainPattern) {
    try {
      const urlHost = new URL(url2).hostname;
      const pattern2 = domainPattern.replace(/\./g, "\\.").replace(/\*/g, ".*");
      const regex = new RegExp(`^${pattern2}$`);
      return regex.test(urlHost);
    } catch (error2) {
      console.error(`[MatchDomain] Invalid URL or pattern:`, url2, domainPattern, error2);
      return false;
    }
  }
  function matchPage(pageUrl, pageMatcher) {
    if (pageMatcher.domains && pageMatcher.domains.length > 0) {
      const domainMatched = pageMatcher.domains.some((domain2) => matchDomain(pageUrl, domain2));
      if (!domainMatched) {
        return false;
      }
    }
    return true;
  }
  function getMatchingRules(pageUrl) {
    return __async(this, null, function* () {
      const config2 = yield getCaptureRules();
      return Object.values(config2).filter((rule) => {
        if (!rule.enabled) {
          return false;
        }
        return matchPage(pageUrl, rule.pageMatcher);
      });
    });
  }
  function matchRequest(request, requestMatcher) {
    if (requestMatcher.urlPatterns && requestMatcher.urlPatterns.length > 0) {
      const urlMatched = requestMatcher.urlPatterns.some((pattern2) => {
        try {
          const regex = new RegExp(pattern2);
          return regex.test(request.url);
        } catch (error2) {
          console.error(`[MatchRequest] Invalid regex pattern: ${pattern2}`, error2);
          return false;
        }
      });
      if (!urlMatched) {
        return false;
      }
    }
    if (requestMatcher.methods && requestMatcher.methods.length > 0) {
      if (!requestMatcher.methods.includes(request.method)) {
        return false;
      }
    }
    return true;
  }
  function shouldCaptureRequest(request, rule) {
    return matchRequest(request, rule.requestMatcher);
  }
  function findMatchingRule(request, rules2) {
    return rules2.find((rule) => shouldCaptureRequest(request, rule)) || null;
  }
  const DEBUGGER_PROTOCOL_VERSION = "1.3";
  class AutoNetworkCaptureService {
    // tabId -> session
    constructor() {
      __publicField2(this, "sessions", /* @__PURE__ */ new Map());
      chrome.debugger.onEvent.addListener(this.handleDebuggerEvent.bind(this));
      chrome.debugger.onDetach.addListener(this.handleDebuggerDetach.bind(this));
    }
    /**
     * 为指定标签页启动捕获
     * @param tabId 标签页 ID
     * @param rules 应用于该标签页的捕获规则列表
     */
    startCaptureForTab(_0) {
      return __async(this, arguments, function* (tabId, rules2 = []) {
        var _a3, _b2;
        try {
          if (this.sessions.has(tabId)) {
            yield this.stopCaptureForTab(tabId);
          }
          const tab = yield chrome.tabs.get(tabId);
          try {
            yield chrome.debugger.attach({ tabId }, DEBUGGER_PROTOCOL_VERSION);
          } catch (error2) {
            if (((_a3 = error2.message) == null ? void 0 : _a3.includes("Cannot attach")) || ((_b2 = error2.message) == null ? void 0 : _b2.includes("attached"))) {
              console.warn(`[AutoNetworkCapture] Debugger already attached to tab ${tabId}`);
              return;
            }
            throw error2;
          }
          try {
            yield chrome.debugger.sendCommand({ tabId }, "Network.enable");
          } catch (error2) {
            yield chrome.debugger.detach({ tabId }).catch(() => {
            });
            throw error2;
          }
          const session = {
            tabId,
            tabUrl: tab.url || "",
            tabTitle: tab.title || "",
            startTime: Date.now(),
            rules: rules2,
            // 保存规则列表
            requests: /* @__PURE__ */ new Map()
          };
          this.sessions.set(tabId, session);
          console.log(
            `[AutoNetworkCapture] Started capture for tab ${tabId} (${tab.url}) with ${rules2.length} rules`
          );
        } catch (error2) {
          console.error(`[AutoNetworkCapture] Failed to start capture for tab ${tabId}:`, error2);
          throw error2;
        }
      });
    }
    /**
     * 停止指定标签页的捕获
     */
    stopCaptureForTab(tabId) {
      return __async(this, null, function* () {
        const session = this.sessions.get(tabId);
        if (!session) {
          return;
        }
        try {
          yield chrome.debugger.sendCommand({ tabId }, "Network.disable");
        } catch (error2) {
          console.warn(`[AutoNetworkCapture] Failed to disable network for tab ${tabId}:`, error2);
        }
        try {
          yield chrome.debugger.detach({ tabId });
        } catch (error2) {
          console.warn(`[AutoNetworkCapture] Failed to detach debugger from tab ${tabId}:`, error2);
        }
        this.sessions.delete(tabId);
        console.log(`[AutoNetworkCapture] Stopped capture for tab ${tabId}`);
      });
    }
    /**
     * 处理 Debugger 事件
     */
    handleDebuggerEvent(source, method, params) {
      const tabId = source.tabId;
      if (!tabId || !this.sessions.has(tabId)) {
        return;
      }
      const session = this.sessions.get(tabId);
      if (method === "Network.requestWillBeSent") {
        this.handleRequestWillBeSent(session, params);
      } else if (method === "Network.responseReceived") {
        this.handleResponseReceived(session, params);
      } else if (method === "Network.loadingFinished") {
        this.handleLoadingFinished(session, params);
      } else if (method === "Network.loadingFailed") {
        this.handleLoadingFailed(session, params);
      }
    }
    /**
     * 处理请求发送事件
     */
    handleRequestWillBeSent(session, params) {
      const { requestId, request, type: type2 } = params;
      const url2 = request.url;
      const method = request.method;
      const networkRequest = {
        url: url2,
        method,
        resourceType: type2
      };
      console.log(`[AutoNetworkCapture] Request sent: ${JSON.stringify(networkRequest)}`);
      const matchedRule = findMatchingRule(networkRequest, session.rules);
      if (!matchedRule) {
        return;
      }
      console.log(`[AutoNetworkCapture] Matched rule "${matchedRule.name}" for: ${method} ${url2}`);
      let host = "";
      let path = "";
      try {
        const urlObj = new URL(url2);
        host = urlObj.hostname;
        path = urlObj.pathname + urlObj.search;
      } catch (error2) {
        console.warn(`[AutoNetworkCapture] Invalid URL: ${url2}`);
        return;
      }
      const capturedReq = {
        requestId,
        url: url2,
        host,
        path,
        method: request.method,
        requestHeaders: matchedRule.options.captureHeaders ? request.headers : void 0,
        requestBody: matchedRule.options.captureRequestBody ? request.postData : void 0,
        timestamp: Date.now(),
        tabId: session.tabId,
        tabUrl: session.tabUrl,
        tabTitle: session.tabTitle,
        matchedRules: [matchedRule.id],
        // 记录匹配的规则 ID
        base64Encoded: false
      };
      session.requests.set(requestId, capturedReq);
    }
    /**
     * 处理响应接收事件
     */
    handleResponseReceived(session, params) {
      const { requestId, response } = params;
      const request = session.requests.get(requestId);
      if (!request) {
        return;
      }
      request.statusCode = response.status;
      request.responseHeaders = response.headers;
      request.mimeType = response.mimeType || "application/octet-stream";
    }
    /**
     * 处理加载完成事件
     */
    handleLoadingFinished(session, params) {
      return __async(this, null, function* () {
        const { requestId, encodedDataLength } = params;
        const request = session.requests.get(requestId);
        if (!request || !request.matchedRules || request.matchedRules.length === 0) {
          return;
        }
        request.size = encodedDataLength || 0;
        const ruleId = request.matchedRules[0];
        const matchedRule = session.rules.find((r) => r.id === ruleId);
        if (!matchedRule) {
          console.warn(`[AutoNetworkCapture] Rule ${ruleId} not found in session rules`);
          session.requests.delete(requestId);
          return;
        }
        const maxSize = matchedRule.options.maxResponseSize || 10 * 1024 * 1024;
        if (request.size && request.size > maxSize) {
          console.warn(
            `[AutoNetworkCapture] Response too large (${request.size} bytes, max: ${maxSize}), skipping: ${request.url}`
          );
          session.requests.delete(requestId);
          return;
        }
        if (matchedRule.options.captureResponseBody !== false) {
          try {
            const responseBody = yield chrome.debugger.sendCommand(
              { tabId: session.tabId },
              "Network.getResponseBody",
              { requestId }
            );
            if (responseBody) {
              request.base64Encoded = responseBody.base64Encoded || false;
              if (!request.base64Encoded && responseBody.body) {
                try {
                  request.responseBody = JSON.parse(responseBody.body);
                } catch (e) {
                  request.responseBody = responseBody.body;
                }
              } else {
                request.responseBody = responseBody.body;
              }
            }
          } catch (error2) {
            console.warn(`[AutoNetworkCapture] Failed to get response body for ${request.url}:`, error2);
          }
        }
        yield this.saveRequest(request);
        session.requests.delete(requestId);
      });
    }
    /**
     * 处理加载失败事件
     */
    handleLoadingFailed(session, params) {
      const { requestId } = params;
      session.requests.delete(requestId);
    }
    /**
     * 保存请求到 IndexedDB
     */
    saveRequest(request) {
      return __async(this, null, function* () {
        try {
          yield capturedRequestsDB.addRequest(request);
          console.log(`[AutoNetworkCapture] Saved request: ${request.method} ${request.url}`);
        } catch (error2) {
          console.error("[AutoNetworkCapture] Failed to save request:", error2);
        }
      });
    }
    /**
     * 处理 Debugger 分离事件
     */
    handleDebuggerDetach(source, reason) {
      const tabId = source.tabId;
      if (!tabId) {
        return;
      }
      console.log(`[AutoNetworkCapture] Debugger detached from tab ${tabId}, reason: ${reason}`);
      this.sessions.delete(tabId);
    }
    /**
     * 清理指定标签页的数据
     */
    cleanupTabData(tabId) {
      return __async(this, null, function* () {
        yield this.stopCaptureForTab(tabId);
        try {
          const deletedCount = yield capturedRequestsDB.deleteByTabId(tabId);
          console.log(`[AutoNetworkCapture] Cleaned up ${deletedCount} requests for tab ${tabId}`);
        } catch (error2) {
          console.error(`[AutoNetworkCapture] Failed to cleanup data for tab ${tabId}:`, error2);
        }
      });
    }
    /**
     * 获取当前状态
     */
    getStatus() {
      return {
        activeSessions: this.sessions.size
      };
    }
  }
  const autoNetworkCaptureService = new AutoNetworkCaptureService();
  function initAutoCaptureListener() {
    chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
      handleAutoCaptureMessage(message, sender, sendResponse);
      return true;
    });
    console.log("[AutoCaptureListener] Initialized");
  }
  function handleAutoCaptureMessage(message, _sender, sendResponse) {
    return __async(this, null, function* () {
      const _a3 = message, { type: type2 } = _a3, params = __objRest(_a3, ["type"]);
      try {
        switch (type2) {
          case BACKGROUND_MESSAGE_TYPES$1.GET_CAPTURED_REQUESTS: {
            const groupedRequests = yield capturedRequestsDB.getGroupedRequests(params);
            sendResponse({ success: true, data: groupedRequests });
            break;
          }
          case BACKGROUND_MESSAGE_TYPES$1.GET_SUCCESSFUL_REQUESTS: {
            const successfulRequests = yield capturedRequestsDB.getSuccessfulRequests();
            sendResponse({ success: true, data: successfulRequests });
            break;
          }
          case BACKGROUND_MESSAGE_TYPES$1.GET_CAPTURE_STATS: {
            const stats = yield capturedRequestsDB.getStats();
            const status = autoNetworkCaptureService.getStatus();
            sendResponse({
              success: true,
              data: __spreadProps(__spreadValues({}, stats), {
                enabled: status.activeSessions > 0,
                // 根据活跃会话数判断是否启用
                activeSessions: status.activeSessions
              })
            });
            break;
          }
          case BACKGROUND_MESSAGE_TYPES$1.CLEAR_CAPTURED_REQUESTS: {
            yield capturedRequestsDB.clearAllRequests();
            sendResponse({ success: true });
            break;
          }
          case BACKGROUND_MESSAGE_TYPES$1.GET_AUTO_CAPTURE_STATUS: {
            const status = autoNetworkCaptureService.getStatus();
            sendResponse({ success: true, data: status });
            break;
          }
          case BACKGROUND_MESSAGE_TYPES$1.PREVIEW_REQUEST: {
            chrome.runtime.sendMessage({
              type: BACKGROUND_MESSAGE_TYPES$1.PREVIEW_REQUEST,
              requestId: params.requestId
            });
            sendResponse({ success: true });
            break;
          }
          default:
            break;
        }
      } catch (error2) {
        console.error("[AutoCaptureListener] Error handling message:", error2);
        sendResponse({
          success: false,
          error: error2.message || "Unknown error"
        });
      }
    });
  }
  class PageCaptureManager {
    constructor() {
      // 记录每个标签页关联的规则
      __publicField2(this, "tabRules", /* @__PURE__ */ new Map());
    }
    /**
     * 初始化页面监听器
     */
    init() {
      console.log("[PageCaptureManager] Initializing...");
      chrome.tabs.onUpdated.addListener(this.handleTabUpdated.bind(this));
      chrome.tabs.onRemoved.addListener(this.handleTabRemoved.bind(this));
      onRulesUpdated(() => {
        console.log("[PageCaptureManager] Rules updated, reloading captures for active tabs...");
        this.reloadAllCaptures();
      });
      console.log("[PageCaptureManager] Initialized");
    }
    /**
     * 处理标签页更新事件
     */
    handleTabUpdated(tabId, changeInfo, tab) {
      return __async(this, null, function* () {
        if (changeInfo.url) {
          console.log(`[PageCaptureManager] Tab ${tabId} navigated to: ${changeInfo.url}`);
          yield this.stopCapture(tabId);
        }
        if (changeInfo.status === "complete" && tab.url) {
          console.log(`[PageCaptureManager] Tab ${tabId} loaded: ${tab.url}`);
          yield this.checkAndStartCapture(tabId, tab.url);
        }
      });
    }
    /**
     * 处理标签页移除事件
     */
    handleTabRemoved(tabId) {
      return __async(this, null, function* () {
        console.log(`[PageCaptureManager] Tab ${tabId} removed`);
        yield this.stopCapture(tabId);
      });
    }
    /**
     * 检查并启动捕获
     */
    checkAndStartCapture(tabId, url2) {
      return __async(this, null, function* () {
        try {
          const matchedRules = yield getMatchingRules(url2);
          if (matchedRules.length === 0) {
            console.log(`[PageCaptureManager] No rules matched for tab ${tabId} (${url2})`);
            return;
          }
          console.log(
            `[PageCaptureManager] Found ${matchedRules.length} matching rules for tab ${tabId}:`,
            matchedRules.map((r) => r.name)
          );
          this.tabRules.set(tabId, matchedRules);
          yield this.startCapture(tabId, matchedRules);
        } catch (error2) {
          console.error(
            `[PageCaptureManager] Error checking/starting capture for tab ${tabId}:`,
            error2
          );
        }
      });
    }
    /**
     * 启动捕获
     */
    startCapture(tabId, rules2) {
      return __async(this, null, function* () {
        try {
          console.log(`[PageCaptureManager] Starting capture for tab ${tabId}...`);
          yield autoNetworkCaptureService.startCaptureForTab(tabId, rules2);
          console.log(`[PageCaptureManager] Capture started for tab ${tabId}`);
        } catch (error2) {
          console.error(`[PageCaptureManager] Failed to start capture for tab ${tabId}:`, error2);
          this.tabRules.delete(tabId);
        }
      });
    }
    /**
     * 停止捕获
     */
    stopCapture(tabId) {
      return __async(this, null, function* () {
        if (!this.tabRules.has(tabId)) {
          return;
        }
        try {
          console.log(`[PageCaptureManager] Stopping capture for tab ${tabId}...`);
          yield autoNetworkCaptureService.stopCaptureForTab(tabId);
          this.tabRules.delete(tabId);
          console.log(`[PageCaptureManager] Capture stopped for tab ${tabId}`);
        } catch (error2) {
          console.error(`[PageCaptureManager] Failed to stop capture for tab ${tabId}:`, error2);
        }
      });
    }
    /**
     * 获取当前活跃的捕获会话数量
     */
    getActiveCaptureCount() {
      return this.tabRules.size;
    }
    /**
     * 获取指定标签页的规则
     */
    getTabRules(tabId) {
      return this.tabRules.get(tabId) || [];
    }
    /**
     * 重新加载所有活跃标签页的捕获
     * 用于规则更新后重新应用
     */
    reloadAllCaptures() {
      return __async(this, null, function* () {
        try {
          const tabs = yield chrome.tabs.query({});
          for (const tab of tabs) {
            if (tab.id && tab.url && tab.status === "complete") {
              yield this.stopCapture(tab.id);
              yield this.checkAndStartCapture(tab.id, tab.url);
            }
          }
          console.log("[PageCaptureManager] All captures reloaded");
        } catch (error2) {
          console.error("[PageCaptureManager] Failed to reload captures:", error2);
        }
      });
    }
  }
  const pageCaptureManager = new PageCaptureManager();
  function initPageCaptureManager() {
    pageCaptureManager.init();
  }
  const _ToolRegistry = class _ToolRegistry {
    constructor() {
      __publicField2(this, "tools", /* @__PURE__ */ new Map());
      this.registerDefaultTools();
    }
    static getInstance() {
      if (!_ToolRegistry.instance) {
        _ToolRegistry.instance = new _ToolRegistry();
      }
      return _ToolRegistry.instance;
    }
    /**
     * 注册所有可用的 tool 实例
     */
    registerDefaultTools() {
      this.register(TOOL_NAMES.BROWSER.NAVIGATE, navigateToolCDP);
      this.register(TOOL_NAMES.BROWSER.CLICK, clickToolCDP);
      this.register(TOOL_NAMES.BROWSER.FILL, fillTool);
      this.register(TOOL_NAMES.BROWSER.KEYBOARD, keyboardTool);
      this.register(TOOL_NAMES.BROWSER.SCREENSHOT, screenshotTool);
      this.register(TOOL_NAMES.BROWSER.SCROLL, scrollTool);
      this.register(TOOL_NAMES.BROWSER.WAIT_FOR_ELEMENT, waitForElementToolCDP);
      this.register(TOOL_NAMES.BROWSER.ACCESSIBILITY_SNAPSHOT, accessibilitySnapshotTool);
      this.register(TOOL_NAMES.BROWSER.SCROLL_INTO_VIEW, scrollIntoViewTool);
      this.register(TOOL_NAMES.BROWSER.INPUT_UPLOAD_FILE, fileUploadToolCDP);
      this.register(TOOL_NAMES.BROWSER.WEB_FETCHER, getWebContentToolCDP);
    }
    /**
     * 注册一个 tool 实例
     */
    register(toolName, toolInstance) {
      this.tools.set(toolName, toolInstance);
      console.log(`[ToolRegistry] Registered tool: ${toolName}`);
    }
    /**
     * 获取 tool 实例
     * @throws {Error} 如果 tool 不存在
     */
    get(toolName) {
      const tool = this.tools.get(toolName);
      if (!tool) {
        throw new Error(`Tool not found: ${toolName}`);
      }
      return tool;
    }
    /**
     * 检查 tool 是否已注册
     */
    has(toolName) {
      return this.tools.has(toolName);
    }
    /**
     * 获取所有已注册的 tool 名称
     */
    getAllToolNames() {
      return Array.from(this.tools.keys());
    }
    /**
     * 获取已注册 tool 的数量
     */
    getToolCount() {
      return this.tools.size;
    }
  };
  __publicField2(_ToolRegistry, "instance");
  let ToolRegistry = _ToolRegistry;
  const toolRegistry = ToolRegistry.getInstance();
  function getExtensionURL(path) {
    return chrome.runtime.getURL(path);
  }
  class TestContextImpl {
    constructor(tabId) {
      __publicField2(this, "stepResults", /* @__PURE__ */ new Map());
      __publicField2(this, "data", /* @__PURE__ */ new Map());
      __publicField2(this, "tabId");
      this.tabId = tabId;
    }
    getPreviousResult() {
      const results = Array.from(this.stepResults.values());
      return results[results.length - 1] || null;
    }
    getStepResult(stepId) {
      return this.stepResults.get(stepId) || null;
    }
    getData(key) {
      return this.data.get(key) || null;
    }
    setData(key, value) {
      this.data.set(key, value);
    }
  }
  class TestExecutor {
    /**
     * 执行完整的测试用例
     */
    executeTestCase(testCase, options) {
      return __async(this, null, function* () {
        var _a3, _b2, _c2, _d2;
        const startTime = Date.now();
        const stepResults = [];
        console.log(`[TestExecutor] Starting test case: ${testCase.name} (ID: ${testCase.id})`);
        console.log(`[TestExecutor] Total steps: ${testCase.steps.length}`);
        console.log("[TestExecutor] Opening SidePanel before test execution...");
        const sidePanelTab = yield chrome.tabs.create({
          url: getExtensionURL("sidepanel.html"),
          active: true
        });
        console.log(`[TestExecutor] SidePanel opened in tab ${sidePanelTab.id}`);
        yield new Promise((resolve2) => setTimeout(resolve2, 1e3));
        const tabId = (options == null ? void 0 : options.tabId) || ((_a3 = testCase.config) == null ? void 0 : _a3.tabId) || (yield this.getCurrentTabId());
        const context = new TestContextImpl(tabId);
        console.log(`[TestExecutor] Target tab ID: ${tabId}`);
        const tabsToClean = /* @__PURE__ */ new Set();
        tabsToClean.add(sidePanelTab.id);
        if (tabId !== sidePanelTab.id) {
          tabsToClean.add(tabId);
        }
        try {
          for (let i2 = 0; i2 < testCase.steps.length; i2++) {
            const step = testCase.steps[i2];
            console.log(
              `[TestExecutor] Executing step ${i2 + 1}/${testCase.steps.length}: ${step.name}`
            );
            const stepResult = yield this.executeStep(step, context);
            stepResults.push(stepResult);
            context.stepResults.set(step.id, stepResult.result);
            if (step.toolName === "chrome_navigate" && !stepResult.result.isError) {
              try {
                if (Array.isArray(stepResult.result.content) && stepResult.result.content.length > 0) {
                  const firstContent = stepResult.result.content[0];
                  if (firstContent.type === "text") {
                    const responseData = JSON.parse(firstContent.text);
                    if (responseData.created && responseData.tabId) {
                      tabsToClean.add(responseData.tabId);
                      console.log(`[TestExecutor] Added tab ${responseData.tabId} to cleanup list`);
                    }
                  }
                }
              } catch (error2) {
                console.warn("[TestExecutor] Failed to parse navigate result for cleanup:", error2);
              }
            }
            (_b2 = options == null ? void 0 : options.onStepComplete) == null ? void 0 : _b2.call(options, i2, stepResult.result);
            (_c2 = options == null ? void 0 : options.onProgress) == null ? void 0 : _c2.call(options, i2 + 1, testCase.steps.length);
            if (!stepResult.success) {
              console.error(`[TestExecutor] Step ${i2 + 1} failed: ${step.name}`);
              console.error(`[TestExecutor] Error:`, stepResult.result.content);
              if (((_d2 = testCase.config) == null ? void 0 : _d2.stopOnError) !== false) {
                let errorMessage = "Step execution failed";
                if (stepResult.result.content && Array.isArray(stepResult.result.content) && stepResult.result.content.length > 0) {
                  const firstContent = stepResult.result.content[0];
                  if (firstContent.type === "text") {
                    errorMessage = firstContent.text;
                  }
                }
                return {
                  testCaseId: testCase.id,
                  success: false,
                  totalSteps: testCase.steps.length,
                  completedSteps: i2 + 1,
                  failedStepId: step.id,
                  stepResults,
                  totalDuration: Date.now() - startTime,
                  error: errorMessage
                };
              }
            }
            if (step.waitAfter) {
              console.log(`[TestExecutor] Waiting ${step.waitAfter}ms after step...`);
              yield new Promise((resolve2) => setTimeout(resolve2, step.waitAfter));
            }
          }
          const totalDuration = Date.now() - startTime;
          console.log(`[TestExecutor] Test case completed successfully in ${totalDuration}ms`);
          return {
            testCaseId: testCase.id,
            success: true,
            totalSteps: testCase.steps.length,
            completedSteps: testCase.steps.length,
            stepResults,
            totalDuration
          };
        } catch (error2) {
          console.error("[TestExecutor] Test case execution error:", error2);
          return {
            testCaseId: testCase.id,
            success: false,
            totalSteps: testCase.steps.length,
            completedSteps: stepResults.length,
            stepResults,
            totalDuration: Date.now() - startTime,
            error: error2 instanceof Error ? error2.message : String(error2)
          };
        } finally {
          console.log("[TestExecutor] Cleaning up tabs...");
          for (const tabIdToClose of tabsToClean) {
            try {
              yield chrome.tabs.remove(tabIdToClose);
              console.log(`[TestExecutor] Closed tab ${tabIdToClose}`);
            } catch (err) {
              console.warn(`[TestExecutor] Failed to close tab ${tabIdToClose}:`, err);
            }
          }
          console.log("[TestExecutor] Tab cleanup completed");
        }
      });
    }
    /**
     * 执行单个步骤
     */
    executeStep(step, context) {
      return __async(this, null, function* () {
        const stepStartTime = Date.now();
        let params = {};
        try {
          const tool = toolRegistry.get(step.toolName);
          if (step.paramsBuilder) {
            console.log(`[TestExecutor] Building params dynamically for step: ${step.name}`);
            params = yield step.paramsBuilder(context);
          } else if (step.params) {
            params = __spreadValues({}, step.params);
          } else {
            params = {};
          }
          if (!params.tabId) {
            params.tabId = context.tabId;
          }
          console.log(`[TestExecutor] Step "${step.name}" params:`, JSON.stringify(params, null, 2));
          const result2 = yield tool.execute(params);
          console.log(
            `[TestExecutor] Step "${step.name}" result:`,
            result2.isError ? "❌ Error" : "✅ Success"
          );
          if (result2.isError) {
            console.log(`[TestExecutor] Error content:`, result2.content);
          }
          if (step.toolName === "chrome_navigate" && !result2.isError) {
            try {
              if (Array.isArray(result2.content) && result2.content.length > 0) {
                const firstContent = result2.content[0];
                if (firstContent.type === "text") {
                  const responseData = JSON.parse(firstContent.text);
                  if (responseData.tabId) {
                    const oldTabId = context.tabId;
                    context.tabId = responseData.tabId;
                    console.log(
                      `[TestExecutor] Auto-updated context.tabId: ${oldTabId} -> ${context.tabId}`
                    );
                  }
                }
              }
            } catch (error2) {
              console.warn("[TestExecutor] Failed to auto-update tabId from navigate result:", error2);
            }
          }
          if (step.extractToContext) {
            console.log(`[TestExecutor] Extracting data to context for step: ${step.name}`);
            yield step.extractToContext(result2, context);
            console.log(
              `[TestExecutor] Context data after extraction:`,
              Object.fromEntries(context.data)
            );
          }
          let success2 = !result2.isError;
          if (step.validate) {
            console.log(`[TestExecutor] Validating result for step: ${step.name}`);
            success2 = step.validate(result2);
            console.log(`[TestExecutor] Validation result: ${success2 ? "✅ Pass" : "❌ Fail"}`);
          }
          const duration2 = Date.now() - stepStartTime;
          console.log(`[TestExecutor] Step completed in ${duration2}ms, success: ${success2}`);
          return {
            stepId: step.id,
            stepName: step.name,
            success: success2,
            result: result2,
            duration: duration2,
            params
            // 包含输入参数
          };
        } catch (error2) {
          const duration2 = Date.now() - stepStartTime;
          console.error(`[TestExecutor] Step error:`, error2);
          return {
            stepId: step.id,
            stepName: step.name,
            success: false,
            result: {
              isError: true,
              content: [
                {
                  type: "text",
                  text: error2 instanceof Error ? error2.message : String(error2)
                }
              ]
            },
            duration: duration2,
            params
            // 包含输入参数
          };
        }
      });
    }
    /**
     * 获取当前活动标签页 ID
     */
    getCurrentTabId() {
      return __async(this, null, function* () {
        const [tab] = yield chrome.tabs.query({ active: true, currentWindow: true });
        if (!(tab == null ? void 0 : tab.id)) {
          throw new Error("No active tab found");
        }
        return tab.id;
      });
    }
  }
  const testExecutor = new TestExecutor();
  const cdpToolsTestCases = [
    // ============================================
    // 搜索测试 (7 个)
    // ============================================
    // 测试 1: 小红书搜索测试
    {
      id: "xiaohongshu-search-test",
      name: "小红书搜索测试",
      description: '测试在小红书搜索"赵露思"',
      tags: ["cdp", "fill", "keyboard", "search", "xiaohongshu"],
      steps: [
        {
          id: "navigate",
          name: "打开小红书探索页",
          toolName: TOOL_NAMES.BROWSER.NAVIGATE,
          params: {
            url: "https://www.xiaohongshu.com/explore"
          },
          waitAfter: 1e3
        },
        {
          id: "wait-for-search-input",
          name: "等待搜索框出现",
          toolName: TOOL_NAMES.BROWSER.WAIT_FOR_ELEMENT,
          params: {
            selector: "#search-input",
            timeout: 1e4,
            visible: true
          },
          validate: (result2) => {
            if (result2.isError) {
              console.error("[小红书搜索测试] ❌ 搜索框未出现");
              return false;
            }
            console.log("[小红书搜索测试] ✅ 搜索框已出现");
            return true;
          }
        },
        {
          id: "fill-search-input",
          name: '在搜索框输入"赵露思"',
          toolName: TOOL_NAMES.BROWSER.FILL,
          params: {
            selector: "#search-input",
            value: "赵露思",
            clearFirst: true
          },
          waitAfter: 1e3,
          validate: (result2) => {
            if (result2.isError) {
              console.error("[小红书搜索测试] ❌ 输入失败");
              return false;
            }
            console.log("[小红书搜索测试] ✅ 输入成功");
            return true;
          }
        },
        {
          id: "press-enter",
          name: "按下回车键搜索",
          toolName: TOOL_NAMES.BROWSER.KEYBOARD,
          params: {
            keys: "Enter",
            selector: "#search-input"
          },
          waitAfter: 2e3,
          validate: (result2) => {
            if (result2.isError) {
              console.error("[小红书搜索测试] ❌ 按键失败");
              return false;
            }
            console.log("[小红书搜索测试] ✅ 搜索执行成功");
            return true;
          }
        }
      ],
      config: {
        stopOnError: true,
        timeout: 4e4
      }
    },
    // 测试 2: Google 搜索测试
    {
      id: "google-search",
      name: "Google 搜索测试",
      description: '在 Google 搜索 "Manus AI Agent" 并滚动到底部',
      tags: ["search", "google", "scroll"],
      steps: [
        {
          id: "navigate",
          name: "导航到 Google",
          toolName: TOOL_NAMES.BROWSER.NAVIGATE,
          params: {
            url: "https://google.com/"
          },
          waitAfter: 1500
        },
        {
          id: "fill-search",
          name: "输入搜索内容",
          toolName: TOOL_NAMES.BROWSER.FILL,
          params: {
            selector: 'textarea[name="q"]',
            value: "Manus AI Agent",
            clearFirst: true
          },
          waitAfter: 500
        },
        {
          id: "press-enter",
          name: "按下回车搜索",
          toolName: TOOL_NAMES.BROWSER.KEYBOARD,
          params: {
            keys: "Enter"
          },
          waitAfter: 2e3
        },
        {
          id: "scroll-to-bottom",
          name: "滚动到底部",
          toolName: TOOL_NAMES.BROWSER.SCROLL,
          params: {
            direction: "down",
            distance: 1e4
          },
          waitAfter: 1e3
        }
      ],
      config: {
        stopOnError: true,
        timeout: 3e4
      }
    },
    // 测试 3: DuckDuckGo 搜索测试
    {
      id: "duckduckgo-search",
      name: "DuckDuckGo 搜索测试",
      description: '在 DuckDuckGo 搜索 "Manus AI Agent"',
      tags: ["search", "duckduckgo"],
      steps: [
        {
          id: "navigate",
          name: "导航到 DuckDuckGo",
          toolName: TOOL_NAMES.BROWSER.NAVIGATE,
          params: {
            url: "https://duckduckgo.com/"
          },
          waitAfter: 1500
        },
        {
          id: "fill-search",
          name: "输入搜索内容",
          toolName: TOOL_NAMES.BROWSER.FILL,
          params: {
            selector: 'input[name="q"]',
            value: "Manus AI Agent",
            clearFirst: true
          },
          waitAfter: 500
        },
        {
          id: "click-submit",
          name: "点击搜索按钮",
          toolName: TOOL_NAMES.BROWSER.CLICK,
          params: {
            selector: 'button[type="submit"]',
            button: "left"
          },
          waitAfter: 2e3
        }
      ],
      config: {
        stopOnError: true,
        timeout: 3e4
      }
    },
    // 测试 4: 百度搜索和滚动测试
    {
      id: "baidu-search-and-scroll",
      name: "百度搜索和滚动测试",
      description: '在百度搜索"人工智能"并多次滚动',
      tags: ["search", "baidu", "scroll"],
      steps: [
        {
          id: "navigate",
          name: "导航到百度",
          toolName: TOOL_NAMES.BROWSER.NAVIGATE,
          params: {
            url: "https://www.baidu.com/"
          },
          waitAfter: 1500
        },
        {
          id: "fill-search",
          name: "输入搜索内容",
          toolName: TOOL_NAMES.BROWSER.FILL,
          params: {
            selector: "#kw",
            value: "人工智能",
            clearFirst: true
          },
          waitAfter: 500
        },
        {
          id: "click-submit",
          name: "点击搜索按钮",
          toolName: TOOL_NAMES.BROWSER.CLICK,
          params: {
            selector: "#chat-submit-button",
            button: "left"
          },
          waitAfter: 2e3
        },
        {
          id: "scroll-1",
          name: "第一次滚动",
          toolName: TOOL_NAMES.BROWSER.SCROLL,
          params: {
            direction: "down",
            distance: 500
          },
          waitAfter: 500
        },
        {
          id: "scroll-2",
          name: "第二次滚动",
          toolName: TOOL_NAMES.BROWSER.SCROLL,
          params: {
            direction: "down",
            distance: 500
          },
          waitAfter: 500
        },
        {
          id: "scroll-to-top",
          name: "滚动到顶部",
          toolName: TOOL_NAMES.BROWSER.SCROLL,
          params: {
            direction: "up",
            distance: 1e4
          },
          waitAfter: 1e3
        }
      ],
      config: {
        stopOnError: true,
        timeout: 4e4
      }
    },
    // 测试 5: Google 搜索滚动测试
    {
      id: "google-search-scroll",
      name: "Google 搜索滚动测试",
      description: "Google 搜索结果页完整滚动（到底 + 到顶）",
      tags: ["search", "google", "scroll"],
      steps: [
        {
          id: "navigate",
          name: "导航到 Google 搜索结果",
          toolName: TOOL_NAMES.BROWSER.NAVIGATE,
          params: {
            url: "https://www.google.com/search?q=Manus+AI+Agent"
          },
          waitAfter: 2e3
        },
        {
          id: "scroll-down",
          name: "滚动到底部",
          toolName: TOOL_NAMES.BROWSER.SCROLL,
          params: {
            direction: "down",
            distance: 1e4
          },
          waitAfter: 1e3
        },
        {
          id: "scroll-up",
          name: "滚动到顶部",
          toolName: TOOL_NAMES.BROWSER.SCROLL,
          params: {
            direction: "up",
            distance: 1e4
          },
          waitAfter: 1e3
        }
      ],
      config: {
        stopOnError: false,
        timeout: 3e4
      }
    },
    // 测试 6: Google 搜索按像素滚动
    {
      id: "google-search-scroll-pixels",
      name: "Google 搜索按像素滚动",
      description: "Google 搜索按视口高度滚动",
      tags: ["search", "google", "scroll", "pixels"],
      steps: [
        {
          id: "navigate",
          name: "导航到 Google 搜索结果",
          toolName: TOOL_NAMES.BROWSER.NAVIGATE,
          params: {
            url: "https://www.google.com/search?q=Manus+AI+Agent"
          },
          waitAfter: 2e3
        },
        {
          id: "scroll-1",
          name: "滚动 720px",
          toolName: TOOL_NAMES.BROWSER.SCROLL,
          params: {
            direction: "down",
            distance: 720
          },
          waitAfter: 500
        },
        {
          id: "scroll-2",
          name: "再滚动 720px",
          toolName: TOOL_NAMES.BROWSER.SCROLL,
          params: {
            direction: "down",
            distance: 720
          },
          waitAfter: 500
        },
        {
          id: "scroll-3",
          name: "再滚动 720px",
          toolName: TOOL_NAMES.BROWSER.SCROLL,
          params: {
            direction: "down",
            distance: 720
          },
          waitAfter: 500
        }
      ],
      config: {
        stopOnError: false,
        timeout: 3e4
      }
    },
    // 测试 7: YouTube 搜索滚动
    {
      id: "youtube-search-jj-lin",
      name: "YouTube 搜索滚动测试",
      description: 'YouTube 搜索 "林俊杰"，完整滚动循环',
      tags: ["search", "youtube", "scroll"],
      steps: [
        {
          id: "navigate",
          name: "导航到 YouTube 搜索结果",
          toolName: TOOL_NAMES.BROWSER.NAVIGATE,
          params: {
            url: "https://www.youtube.com/results?search_query=林俊杰"
          },
          waitAfter: 3e3
        },
        {
          id: "scroll-down",
          name: "滚动到底部",
          toolName: TOOL_NAMES.BROWSER.SCROLL,
          params: {
            direction: "down",
            distance: 1e4
          },
          waitAfter: 2e3
        },
        {
          id: "scroll-up",
          name: "滚动到顶部",
          toolName: TOOL_NAMES.BROWSER.SCROLL,
          params: {
            direction: "up",
            distance: 1e4
          },
          waitAfter: 1e3
        }
      ],
      config: {
        stopOnError: false,
        timeout: 4e4
      }
    },
    // ============================================
    // 滚动测试 (3 个)
    // ============================================
    // // 测试 8: Gmail 收件箱滚动
    // {
    //   id: 'gmail-inbox-scroll',
    //   name: 'Gmail 收件箱滚动测试',
    //   description: 'Gmail 收件箱向下滚动一屏',
    //   tags: ['scroll', 'gmail'],
    //   steps: [
    //     {
    //       id: 'navigate',
    //       name: '导航到 Gmail',
    //       toolName: TOOL_NAMES.BROWSER.NAVIGATE,
    //       params: {
    //         url: 'https://mail.google.com/',
    //       },
    //       waitAfter: 3000,
    //     },
    //     {
    //       id: 'scroll-down',
    //       name: '向下滚动',
    //       toolName: TOOL_NAMES.BROWSER.SCROLL,
    //       params: {
    //         direction: 'down',
    //         distance: 720,
    //       },
    //       waitAfter: 1000,
    //     },
    //   ],
    //   config: {
    //     stopOnError: false,
    //     timeout: 30000,
    //   },
    // },
    // 测试 9: YouTube 键盘滚动
    {
      id: "youtube-scroll-pagekey",
      name: "YouTube 键盘滚动测试",
      description: "YouTube 新闻频道使用 PageDown/Up 滚动",
      tags: ["scroll", "youtube", "keyboard"],
      steps: [
        {
          id: "navigate",
          name: "导航到 YouTube 新闻",
          toolName: TOOL_NAMES.BROWSER.NAVIGATE,
          params: {
            url: "https://www.youtube.com/feed/trending"
          },
          waitAfter: 3e3
        },
        {
          id: "pagedown-1",
          name: "PageDown 1",
          toolName: TOOL_NAMES.BROWSER.KEYBOARD,
          params: {
            keys: "PageDown"
          },
          waitAfter: 500
        },
        {
          id: "pagedown-2",
          name: "PageDown 2",
          toolName: TOOL_NAMES.BROWSER.KEYBOARD,
          params: {
            keys: "PageDown"
          },
          waitAfter: 500
        },
        {
          id: "pagedown-3",
          name: "PageDown 3",
          toolName: TOOL_NAMES.BROWSER.KEYBOARD,
          params: {
            keys: "PageDown"
          },
          waitAfter: 500
        },
        {
          id: "pageup-1",
          name: "PageUp 1",
          toolName: TOOL_NAMES.BROWSER.KEYBOARD,
          params: {
            keys: "PageUp"
          },
          waitAfter: 500
        },
        {
          id: "pageup-2",
          name: "PageUp 2",
          toolName: TOOL_NAMES.BROWSER.KEYBOARD,
          params: {
            keys: "PageUp"
          },
          waitAfter: 500
        }
      ],
      config: {
        stopOnError: false,
        timeout: 4e4
      }
    },
    // 测试 10: 持续滚动压力测试（简化版）
    {
      id: "continuous-scroll-test",
      name: "持续滚动压力测试",
      description: "多次滚动到底部和顶部的循环测试（10次）",
      tags: ["scroll", "performance", "stress"],
      steps: [
        {
          id: "navigate",
          name: "导航到测试页面",
          toolName: TOOL_NAMES.BROWSER.NAVIGATE,
          params: {
            url: "https://www.wikipedia.org/"
          },
          waitAfter: 2e3
        },
        // 简化版：10次循环而非300次
        ...Array.from({ length: 10 }, (_, i2) => [
          {
            id: `scroll-down-${i2 + 1}`,
            name: `向下滚动 ${i2 + 1}`,
            toolName: TOOL_NAMES.BROWSER.SCROLL,
            params: {
              direction: "down",
              distance: 1e3
            },
            waitAfter: 100
          },
          {
            id: `scroll-up-${i2 + 1}`,
            name: `向上滚动 ${i2 + 1}`,
            toolName: TOOL_NAMES.BROWSER.SCROLL,
            params: {
              direction: "up",
              distance: 1e3
            },
            waitAfter: 100
          }
        ]).flat()
      ],
      config: {
        stopOnError: false,
        timeout: 12e4
      }
    },
    // ============================================
    // 键盘测试 (2 个)
    // ============================================
    // 测试 11: 完整键盘测试
    {
      id: "full-keyboard-test",
      name: "完整键盘测试",
      description: "在键盘测试网站按下所有键（F1-F12, 字母, 数字, 符号, 小键盘等）",
      tags: ["keyboard", "comprehensive"],
      steps: [
        {
          id: "navigate",
          name: "导航到键盘测试网站",
          toolName: TOOL_NAMES.BROWSER.NAVIGATE,
          params: {
            url: "https://www.zfrontier.com/lab/keyboardTester"
          },
          waitAfter: 2e3
        },
        // 功能键
        ...["Escape", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12"].map(
          (key) => ({
            id: `key-${key.toLowerCase()}`,
            name: `按下 ${key}`,
            toolName: TOOL_NAMES.BROWSER.KEYBOARD,
            params: { keys: key },
            waitAfter: 50
          })
        ),
        // 数字和符号行
        ...["`", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "-", "=", "Backspace"].map(
          (key) => ({
            id: `key-${key === "`" ? "backtick" : key === "-" ? "minus" : key === "=" ? "equal" : key.toLowerCase()}`,
            name: `按下 ${key}`,
            toolName: TOOL_NAMES.BROWSER.KEYBOARD,
            params: { keys: key },
            waitAfter: 50
          })
        ),
        // 字母键
        ..."QWERTYUIOPASDFGHJKLZXCVBNM".split("").map((key) => ({
          id: `key-${key.toLowerCase()}`,
          name: `按下 ${key}`,
          toolName: TOOL_NAMES.BROWSER.KEYBOARD,
          params: { keys: key },
          waitAfter: 50
        })),
        // 特殊键
        ...["Tab", "CapsLock", "Enter", "Shift", "Control", "Alt", "Meta", "Space"].map((key) => ({
          id: `key-${key.toLowerCase()}`,
          name: `按下 ${key}`,
          toolName: TOOL_NAMES.BROWSER.KEYBOARD,
          params: { keys: key },
          waitAfter: 50
        })),
        // 导航键
        ...["Insert", "Home", "PageUp", "Delete", "End", "PageDown"].map((key) => ({
          id: `key-${key.toLowerCase()}`,
          name: `按下 ${key}`,
          toolName: TOOL_NAMES.BROWSER.KEYBOARD,
          params: { keys: key },
          waitAfter: 50
        })),
        // 方向键
        ...["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"].map((key) => ({
          id: `key-${key.toLowerCase()}`,
          name: `按下 ${key}`,
          toolName: TOOL_NAMES.BROWSER.KEYBOARD,
          params: { keys: key },
          waitAfter: 50
        }))
      ],
      config: {
        stopOnError: false,
        timeout: 12e4
      }
    },
    // 测试 12: 组合键测试
    {
      id: "key-combinations-test",
      name: "组合键测试",
      description: "测试各种组合键 (Ctrl+C, Cmd+V, Shift+End 等)",
      tags: ["keyboard", "combinations", "modifiers"],
      steps: [
        {
          id: "navigate",
          name: "导航到键盘测试网站",
          toolName: TOOL_NAMES.BROWSER.NAVIGATE,
          params: {
            url: "https://www.zfrontier.com/lab/keyboardTester"
          },
          waitAfter: 2e3
        },
        // Ctrl 组合键
        ...["Ctrl+A", "Ctrl+C", "Ctrl+V", "Ctrl+X", "Ctrl+Z", "Ctrl+Y"].map((keys) => ({
          id: `combo-${keys.toLowerCase().replace("+", "-")}`,
          name: `按下 ${keys}`,
          toolName: TOOL_NAMES.BROWSER.KEYBOARD,
          params: { keys },
          waitAfter: 100
        })),
        // Shift 组合键
        ...["Shift+Home", "Shift+End", "Shift+ArrowLeft", "Shift+ArrowRight"].map((keys) => ({
          id: `combo-${keys.toLowerCase().replace("+", "-")}`,
          name: `按下 ${keys}`,
          toolName: TOOL_NAMES.BROWSER.KEYBOARD,
          params: { keys },
          waitAfter: 100
        })),
        // Alt 组合键
        ...["Alt+ArrowLeft", "Alt+ArrowRight", "Alt+F4"].map((keys) => ({
          id: `combo-${keys.toLowerCase().replace("+", "-")}`,
          name: `按下 ${keys}`,
          toolName: TOOL_NAMES.BROWSER.KEYBOARD,
          params: { keys },
          waitAfter: 100
        })),
        // Meta 组合键 (macOS)
        ...["Meta+A", "Meta+C", "Meta+V"].map((keys) => ({
          id: `combo-${keys.toLowerCase().replace("+", "-")}`,
          name: `按下 ${keys}`,
          toolName: TOOL_NAMES.BROWSER.KEYBOARD,
          params: { keys },
          waitAfter: 100
        }))
      ],
      config: {
        stopOnError: false,
        timeout: 6e4
      }
    },
    // ============================================
    // 点击测试 (1 个)
    // ============================================
    // // 测试 13: 坐标点击测试
    // {
    //   id: 'playground-click-test',
    //   name: '测试页面坐标点击',
    //   description: '在本地测试页面按坐标点击 6 个按钮',
    //   tags: ['click', 'coordinates', 'playground'],
    //   steps: [
    //     {
    //       id: 'navigate',
    //       name: '导航到测试页面',
    //       toolName: TOOL_NAMES.BROWSER.NAVIGATE,
    //       params: {
    //         url: 'http://localhost:5173/click-playground',
    //       },
    //       waitAfter: 1500,
    //     },
    //     // 左列按钮
    //     {
    //       id: 'click-1',
    //       name: '点击左上按钮',
    //       toolName: TOOL_NAMES.BROWSER.CLICK,
    //       params: {
    //         coordinates: { x: 140, y: 188 },
    //         button: 'left',
    //       },
    //       waitAfter: 300,
    //     },
    //     {
    //       id: 'click-2',
    //       name: '点击左中按钮',
    //       toolName: TOOL_NAMES.BROWSER.CLICK,
    //       params: {
    //         coordinates: { x: 140, y: 288 },
    //         button: 'left',
    //       },
    //       waitAfter: 300,
    //     },
    //     {
    //       id: 'click-3',
    //       name: '点击左下按钮',
    //       toolName: TOOL_NAMES.BROWSER.CLICK,
    //       params: {
    //         coordinates: { x: 140, y: 388 },
    //         button: 'left',
    //       },
    //       waitAfter: 300,
    //     },
    //     // 右列按钮
    //     {
    //       id: 'click-4',
    //       name: '点击右上按钮',
    //       toolName: TOOL_NAMES.BROWSER.CLICK,
    //       params: {
    //         coordinates: { x: 290, y: 188 },
    //         button: 'left',
    //       },
    //       waitAfter: 300,
    //     },
    //     {
    //       id: 'click-5',
    //       name: '点击右中按钮',
    //       toolName: TOOL_NAMES.BROWSER.CLICK,
    //       params: {
    //         coordinates: { x: 290, y: 288 },
    //         button: 'left',
    //       },
    //       waitAfter: 300,
    //     },
    //     {
    //       id: 'click-6',
    //       name: '点击右下按钮',
    //       toolName: TOOL_NAMES.BROWSER.CLICK,
    //       params: {
    //         coordinates: { x: 290, y: 388 },
    //         button: 'left',
    //       },
    //       waitAfter: 300,
    //     },
    //   ],
    //   config: {
    //     stopOnError: false,
    //     timeout: 30000,
    //   },
    // },
    // ============================================
    // 其他测试 (3 个)
    // ============================================
    // 测试 15: 浏览器截图测试
    {
      id: "browser-view-test",
      name: "浏览器截图测试",
      description: "测试页面截图功能",
      tags: ["screenshot", "view"],
      steps: [
        {
          id: "navigate",
          name: "导航到 Example",
          toolName: TOOL_NAMES.BROWSER.NAVIGATE,
          params: {
            url: "https://example.com/"
          },
          waitAfter: 2e3
        },
        {
          id: "screenshot",
          name: "截图",
          toolName: TOOL_NAMES.BROWSER.SCREENSHOT,
          params: {
            storeBase64: true
          },
          waitAfter: 500
        }
      ],
      config: {
        stopOnError: true,
        timeout: 3e4
      }
    },
    // 测试 16: 跟随链接
    {
      id: "example-follow-link",
      name: "跟随链接测试",
      description: '在 example.com 点击 "More Information" 链接',
      tags: ["click", "link", "navigation"],
      steps: [
        {
          id: "navigate",
          name: "导航到 Example",
          toolName: TOOL_NAMES.BROWSER.NAVIGATE,
          params: {
            url: "https://example.com/"
          },
          waitAfter: 2e3
        },
        {
          id: "click-link",
          name: "点击 More Information 链接",
          toolName: TOOL_NAMES.BROWSER.CLICK,
          params: {
            selector: "a",
            button: "left"
          },
          waitAfter: 2e3
        }
      ],
      config: {
        stopOnError: false,
        timeout: 3e4
      }
    },
    // ============================================
    // 状态测试 (2 个)
    // ============================================
    // 测试 18: 错误状态测试
    {
      id: "test-error-status",
      name: "错误状态测试",
      description: "测试 session 错误状态处理",
      tags: ["status", "error"],
      steps: [
        {
          id: "navigate",
          name: "导航到测试页面",
          toolName: TOOL_NAMES.BROWSER.NAVIGATE,
          params: {
            url: "https://example.com/"
          },
          waitAfter: 2e3
        },
        {
          id: "invalid-selector",
          name: "尝试点击不存在的元素",
          toolName: TOOL_NAMES.BROWSER.CLICK,
          params: {
            selector: "#this-does-not-exist-12345",
            button: "left"
          },
          validate: (result2) => {
            return result2.isError;
          }
        }
      ],
      config: {
        stopOnError: false,
        timeout: 3e4
      }
    },
    // ============================================
    // 生命周期测试 (1 个)
    // ============================================
    // 测试 19: Session 生命周期测试
    {
      id: "test-session-lifecycle",
      name: "Session 生命周期测试",
      description: "完整生命周期：多次 running → stopped → running 转换",
      tags: ["lifecycle", "session", "status"],
      steps: [
        {
          id: "navigate",
          name: "导航到 Playwright 网站",
          toolName: TOOL_NAMES.BROWSER.NAVIGATE,
          params: {
            url: "https://playwright.dev/"
          },
          waitAfter: 2e3
        },
        {
          id: "scroll-down-1",
          name: "Task Step 1: 滚动到底",
          toolName: TOOL_NAMES.BROWSER.SCROLL,
          params: {
            direction: "down",
            distance: 1e4
          },
          waitAfter: 1e3
        },
        {
          id: "scroll-up-1",
          name: "Task Step 2: 滚动到顶",
          toolName: TOOL_NAMES.BROWSER.SCROLL,
          params: {
            direction: "up",
            distance: 1e4
          },
          waitAfter: 1e3
        },
        {
          id: "screenshot",
          name: "Task Step 3: 截图",
          toolName: TOOL_NAMES.BROWSER.SCREENSHOT,
          params: {
            storeBase64: true
          },
          waitAfter: 500
        },
        // 停止后重启
        {
          id: "scroll-down-2",
          name: "Task Step 4: 再次滚动到底",
          toolName: TOOL_NAMES.BROWSER.SCROLL,
          params: {
            direction: "down",
            distance: 1e4
          },
          waitAfter: 1e3
        }
      ],
      config: {
        stopOnError: false,
        timeout: 6e4
      }
    },
    // ============================================
    // 辅助功能测试 (1 个)
    // ============================================
    // 测试 20: 辅助功能快照测试
    {
      id: "accessibility-snapshot-test",
      name: "辅助功能快照测试",
      description: "测试页面可点击元素捕获功能",
      tags: ["cdp", "accessibility", "snapshot"],
      steps: [
        {
          id: "navigate",
          name: "导航到百度首页",
          toolName: TOOL_NAMES.BROWSER.NAVIGATE,
          params: {
            url: "https://www.baidu.com/"
          },
          waitAfter: 2e3
        },
        {
          id: "capture-snapshot",
          name: "捕获可点击元素快照",
          toolName: TOOL_NAMES.BROWSER.ACCESSIBILITY_SNAPSHOT,
          params: {},
          waitAfter: 1e3,
          validate: (result2) => {
            if (result2.isError) {
              console.error("[快照测试] ❌ 快照捕获失败");
              return false;
            }
            console.log("[快照测试] ✅ 快照捕获成功");
            return true;
          }
        }
      ],
      config: {
        stopOnError: true,
        timeout: 3e4
      }
    },
    // ============================================
    // 内容获取测试 (1 个)
    // ============================================
    // 测试 21: 网页内容获取测试
    {
      id: "get-web-content-test",
      name: "网页内容获取测试",
      description: "测试获取网页 HTML 并上传功能",
      tags: ["cdp", "content", "upload"],
      steps: [
        {
          id: "get-full-page",
          name: "获取 Example.com 完整 HTML",
          toolName: TOOL_NAMES.BROWSER.WEB_FETCHER,
          params: {
            url: "https://example.com/"
          },
          waitAfter: 2e3,
          validate: (result2) => {
            if (result2.isError) {
              console.error("[内容获取] ❌ 获取失败");
              return false;
            }
            console.log("[内容获取] ✅ 获取成功");
            return true;
          }
        }
      ],
      config: {
        stopOnError: true,
        timeout: 3e4
      }
    },
    // ============================================
    // 元素滚动测试 (1 个)
    // ============================================
    // 测试 22: 元素滚动到视图测试
    {
      id: "scroll-into-view-test",
      name: "元素滚动到视图测试",
      description: "测试将页面底部元素滚动到视图中",
      tags: ["cdp", "scroll", "element"],
      steps: [
        {
          id: "navigate",
          name: "导航到维基百科",
          toolName: TOOL_NAMES.BROWSER.NAVIGATE,
          params: {
            url: "https://zh.wikipedia.org/wiki/人工智能"
          },
          waitAfter: 2e3
        },
        {
          id: "scroll-to-element",
          name: '滚动到页面底部的"参考资料"',
          toolName: TOOL_NAMES.BROWSER.SCROLL_INTO_VIEW,
          params: {
            selector: "#footer-places-about",
            block: "center",
            inline: "center"
          },
          waitAfter: 1e3,
          validate: (result2) => {
            if (result2.isError) {
              console.error("[滚动测试] ❌ 滚动失败");
              return false;
            }
            console.log("[滚动测试] ✅ 滚动成功");
            return true;
          }
        },
        {
          id: "scroll-to-top",
          name: "滚动到页面顶部标题",
          toolName: TOOL_NAMES.BROWSER.SCROLL_INTO_VIEW,
          params: {
            selector: "h1",
            block: "start"
          },
          waitAfter: 1e3
        }
      ],
      config: {
        stopOnError: false,
        timeout: 3e4
      }
    },
    // ============================================
    // 文件上传测试 (1 个)
    // ============================================
    // 测试 23: 文件上传测试
    {
      id: "file-upload-test",
      name: "文件上传测试",
      description: "测试文件上传功能（使用 base64 数据）",
      tags: ["cdp", "upload", "file"],
      steps: [
        {
          id: "navigate",
          name: "导航到文件上传测试网站",
          toolName: TOOL_NAMES.BROWSER.NAVIGATE,
          params: {
            url: "https://the-internet.herokuapp.com/upload"
          },
          waitAfter: 2e3
        },
        {
          id: "upload-file",
          name: "上传测试文件",
          toolName: TOOL_NAMES.BROWSER.INPUT_UPLOAD_FILE,
          params: {
            sourceType: "base64",
            base64Data: "VGVzdCBGaWxlIENvbnRlbnQ=",
            // "Test File Content"
            filename: "test.txt",
            mimeType: "text/plain",
            inputSelector: "#file-upload"
          },
          waitAfter: 1e3,
          validate: (result2) => {
            if (result2.isError) {
              console.error("[上传测试] ❌ 上传失败");
              return false;
            }
            console.log("[上传测试] ✅ 上传成功");
            return true;
          }
        }
        // {
        //   id: 'click-upload-button',
        //   name: '点击上传按钮',
        //   toolName: TOOL_NAMES.BROWSER.CLICK,
        //   params: {
        //     selector: '#file-submit',
        //     button: 'left',
        //   },
        //   waitAfter: 2000,
        // },
      ],
      config: {
        stopOnError: true,
        timeout: 3e4
      }
    }
  ];
  class ToolTestHandler {
    constructor() {
      __publicField2(this, "testCaseRegistry", /* @__PURE__ */ new Map([
        // ['performance', performanceTestCases],
        ["cdp-tools", cdpToolsTestCases]
        // 未来可以添加其他 tool 的测试用例
        // ['click', clickTestCases],
        // ['fill', fillTestCases],
        // ['keyboard', keyboardTestCases],
      ]));
    }
    /**
     * 获取所有测试用例
     */
    handleGetTestCases(filter) {
      return __async(this, null, function* () {
        let allTestCases = [];
        for (const cases of this.testCaseRegistry.values()) {
          allTestCases = allTestCases.concat(cases);
        }
        if (filter == null ? void 0 : filter.tool) {
          const toolCases = this.testCaseRegistry.get(filter.tool);
          if (toolCases) {
            allTestCases = toolCases;
          } else {
            allTestCases = [];
          }
        }
        if (filter == null ? void 0 : filter.tag) {
          allTestCases = allTestCases.filter((tc) => {
            var _a3;
            return (_a3 = tc.tags) == null ? void 0 : _a3.includes(filter.tag);
          });
        }
        console.log(`[ToolTestHandler] Found ${allTestCases.length} test cases`);
        return {
          ok: true,
          testCases: allTestCases.map((tc) => ({
            id: tc.id,
            name: tc.name,
            description: tc.description,
            tags: tc.tags,
            stepCount: tc.steps.length,
            steps: tc.steps.map((s) => ({
              id: s.id,
              name: s.name,
              toolName: s.toolName
            }))
          }))
        };
      });
    }
    /**
     * 执行测试用例
     */
    handleExecuteTestCase(request) {
      return __async(this, null, function* () {
        console.log(`[ToolTestHandler] Executing test case: ${request.testCaseId}`);
        let testCase;
        for (const cases of this.testCaseRegistry.values()) {
          testCase = cases.find((tc) => tc.id === request.testCaseId);
          if (testCase) break;
        }
        if (!testCase) {
          console.error(`[ToolTestHandler] Test case not found: ${request.testCaseId}`);
          return {
            ok: false,
            error: `Test case not found: ${request.testCaseId}`
          };
        }
        try {
          const result2 = yield testExecutor.executeTestCase(testCase, {
            tabId: request.tabId
          });
          console.log(
            `[ToolTestHandler] Test case execution ${result2.success ? "succeeded" : "failed"}`
          );
          return {
            ok: result2.success,
            result: result2
          };
        } catch (error2) {
          console.error("[ToolTestHandler] Test case execution error:", error2);
          return {
            ok: false,
            error: error2 instanceof Error ? error2.message : String(error2)
          };
        }
      });
    }
  }
  const toolTestHandler = new ToolTestHandler();
  chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.type === "tool-test/get-test-cases") {
      console.log("[ToolTestHandler] Received get-test-cases request");
      toolTestHandler.handleGetTestCases(message.filter).then((result2) => {
        console.log("[ToolTestHandler] Sending response:", result2);
        sendResponse(result2);
      }).catch((error2) => {
        console.error("[ToolTestHandler] Error getting test cases:", error2);
        sendResponse({ ok: false, error: error2.message });
      });
      return true;
    }
    if (message.type === "tool-test/execute-test-case") {
      toolTestHandler.handleExecuteTestCase(message).then(sendResponse).catch((error2) => {
        console.error("[ToolTestHandler] Error executing test case:", error2);
        sendResponse({ ok: false, error: error2.message });
      });
      return true;
    }
    return false;
  });
  console.log("[ToolTestHandler] Initialized");
  const definition = defineBackground(() => {
    browser$1.action.onClicked.addListener((tab) => {
      chrome.sidePanel.open({ windowId: tab.windowId });
    });
    (() => __async(null, null, function* () {
      try {
        console.log("[Background] 启动时加载捕获规则...");
        yield updateCaptureRules({ respectTTL: true, silent: true });
        console.log("[Background] 捕获规则加载完成");
      } catch (error2) {
        console.error("[Background] 启动时加载捕获规则失败:", error2);
      }
    }))();
    initStorageManagerListener();
    initWebSocketLatencyListener();
    initImageFetcherListener();
    initChatAgentListener();
    initAutoCaptureListener();
    initSessionEvents();
    initPageCaptureManager();
    initBackgroundRequestModifier();
    initWebSocketMCPListener();
    initTabSwitchListener();
    chrome.runtime.onInstalled.addListener((details) => {
      if (details.reason === "update") {
        console.log("[Background] 扩展已更新，强制更新捕获规则...");
        updateCaptureRules({ forceUpdate: true, silent: true }).then(() => {
          console.log("[Background] 捕获规则更新完成");
        }).catch((error2) => {
          console.error("[Background] 更新捕获规则失败:", error2);
        });
      }
    });
    chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
      var _a3, _b2;
      if (message && message.type === "get-tab-id") {
        const tabId = (_b2 = (_a3 = _sender.tab) == null ? void 0 : _a3.id) != null ? _b2 : -1;
        sendResponse({ tabId });
        return true;
      }
      if (message && message.type === "init_websocket_mcp") {
        return handleAsyncMessage(
          () => __async(null, null, function* () {
            yield initWebSocketMCPListener();
            const status = getMCPStatus();
            return { ok: true, status };
          }),
          sendResponse,
          3e4
          // 30秒超时
        );
      }
      if (message && message.type === "update_capture_rules") {
        return handleAsyncMessage(
          () => __async(null, null, function* () {
            console.log("[Background] 收到规则更新请求（来自 sidepanel）");
            const rules2 = yield updateCaptureRules({ forceUpdate: true, silent: true });
            return { ok: true, rulesCount: Object.keys(rules2).length };
          }),
          sendResponse,
          3e4
          // 30秒超时
        );
      }
      if (message && message.type === "recording:start") {
        (() => __async(null, null, function* () {
          try {
            console.error("开始录制");
            const { startRecording: startRecording2, registerRecordingEventListeners: registerRecordingEventListeners2 } = yield Promise.resolve().then(() => index);
            registerRecordingEventListeners2();
            yield startRecording2(message.data);
            sendResponse({ success: true });
          } catch (error2) {
            console.error("[Background] 开始录制失败:", error2);
            sendResponse({
              success: false,
              error: error2 instanceof Error ? error2.message : String(error2)
            });
          }
        }))();
        return true;
      }
      if (message && message.type === "recording:stop") {
        (() => __async(null, null, function* () {
          try {
            const { stopRecording: stopRecording2, unregisterRecordingEventListeners: unregisterRecordingEventListeners2 } = yield Promise.resolve().then(() => index);
            const recording = yield stopRecording2();
            unregisterRecordingEventListeners2();
            sendResponse({ success: true, recording });
          } catch (error2) {
            console.error("[Background] 停止录制失败:", error2);
            sendResponse({
              success: false,
              error: error2 instanceof Error ? error2.message : String(error2)
            });
          }
        }))();
        return true;
      }
      if (message && message.type === "recording:export") {
        (() => __async(null, null, function* () {
          var _a4, _b3;
          try {
            const { getRecordingState: getRecordingState2, convertFlowsToDrawflow: convertFlowsToDrawflow2, exportToAutomaJson: exportToAutomaJson2 } = yield Promise.resolve().then(() => index);
            const state = yield getRecordingState2();
            if (state) {
              const workflow = convertFlowsToDrawflow2(state.flows, ((_a4 = message.data) == null ? void 0 : _a4.name) || state.name);
              const json2 = exportToAutomaJson2(workflow);
              sendResponse({ success: true, json: json2, workflow });
            } else {
              const result2 = yield chrome.storage.local.get("recording");
              if (result2.recording) {
                const workflow = convertFlowsToDrawflow2(
                  result2.recording.flows,
                  ((_b3 = message.data) == null ? void 0 : _b3.name) || result2.recording.name
                );
                const json2 = exportToAutomaJson2(workflow);
                sendResponse({ success: true, json: json2, workflow });
              } else {
                sendResponse({ success: false, error: "No recording found" });
              }
            }
          } catch (error2) {
            console.error("[Background] 导出录制失败:", error2);
            sendResponse({
              success: false,
              error: error2 instanceof Error ? error2.message : String(error2)
            });
          }
        }))();
        return true;
      }
      if (message && message.type === "recording:clear") {
        (() => __async(null, null, function* () {
          try {
            const { clearRecording: clearRecording2 } = yield Promise.resolve().then(() => index);
            yield clearRecording2();
            sendResponse({ success: true });
          } catch (error2) {
            console.error("[Background] 清除录制数据失败:", error2);
            sendResponse({
              success: false,
              error: error2 instanceof Error ? error2.message : String(error2)
            });
          }
        }))();
        return true;
      }
      if (message && message.type === "element-picker:start") {
        (() => __async(null, null, function* () {
          try {
            const [activeTab] = yield chrome.tabs.query({ active: true, currentWindow: true });
            if (activeTab == null ? void 0 : activeTab.id) {
              yield chrome.tabs.sendMessage(activeTab.id, { type: "element-picker:start" });
              sendResponse({ success: true });
            } else {
              sendResponse({ success: false, error: "No active tab" });
            }
          } catch (error2) {
            console.error("[Background] 启动元素选择器失败:", error2);
            sendResponse({
              success: false,
              error: error2 instanceof Error ? error2.message : String(error2)
            });
          }
        }))();
        return true;
      }
      if (message && message.type === "element-picker:stop") {
        (() => __async(null, null, function* () {
          try {
            const [activeTab] = yield chrome.tabs.query({ active: true, currentWindow: true });
            if (activeTab == null ? void 0 : activeTab.id) {
              yield chrome.tabs.sendMessage(activeTab.id, { type: "element-picker:stop" });
            }
            sendResponse({ success: true });
          } catch (error2) {
            sendResponse({ success: false, error: String(error2) });
          }
        }))();
        return true;
      }
      if (message && message.type === "open-sidepanel") {
        chrome.windows.getCurrent((currentWindow) => {
          if (currentWindow == null ? void 0 : currentWindow.id) {
            chrome.sidePanel.open({ windowId: currentWindow.id }).then(() => {
              console.log("[Background] Opened sidepanel for window:", currentWindow.id);
              sendResponse({ success: true });
            }).catch((error2) => {
              console.error("[Background] Failed to open sidepanel:", error2);
              sendResponse({
                success: false,
                error: error2.message
              });
            });
          } else {
            sendResponse({ success: false, error: "No window found" });
          }
        });
        return true;
      }
      if (message && message.type === "element-picker:selected") {
        (() => __async(null, null, function* () {
          try {
            const { STORAGE_KEYS: STORAGE_KEYS2 } = yield Promise.resolve().then(() => index$1);
            const result2 = yield chrome.storage.local.get([
              STORAGE_KEYS2.IS_RECORDING,
              STORAGE_KEYS2.RECORDING
            ]);
            if (result2[STORAGE_KEYS2.RECORDING]) {
              const recording = result2[STORAGE_KEYS2.RECORDING];
              recording.flows.push(message.data);
              yield chrome.storage.local.set({ [STORAGE_KEYS2.RECORDING]: recording });
            }
            sendResponse({ success: true });
          } catch (error2) {
            sendResponse({ success: false, error: String(error2) });
          }
        }))();
        return true;
      }
      if (message && message.action) {
        switch (message.action) {
          case "START_TAKEOVER":
            console.log("[Background] START_TAKEOVER 收到开始接管请求", message);
            return handleAsyncMessage(
              () => __async(null, null, function* () {
                var _a4;
                const { getSessionManager: getSessionManager2 } = yield Promise.resolve().then(() => index$2);
                const { notifyTakeoverStart: notifyTakeoverStart2 } = yield Promise.resolve().then(() => sessionApi);
                const manager = getSessionManager2();
                let sessionId = message.sessionId;
                const tabId = (message == null ? void 0 : message.tabId) || ((_a4 = _sender.tab) == null ? void 0 : _a4.id);
                if (!sessionId && tabId) {
                  const session = yield manager.getSessionByTabId(tabId);
                  sessionId = session == null ? void 0 : session.sessionId;
                }
                if (!sessionId) {
                  console.warn("[Background] START_TAKEOVER: 无法获取 sessionId");
                  throw new Error("无法获取当前会话");
                }
                const apiSuccess = yield notifyTakeoverStart2(sessionId, tabId ? String(tabId) : "");
                if (!apiSuccess) {
                  console.error("[Background] 接管 API 调用失败");
                  throw new Error("接管请求失败");
                }
                console.log(`[Background] 接管成功: ${sessionId}`);
                return { success: true, sessionId };
              }),
              sendResponse,
              3e4
              // 30秒超时
            );
          case "EXIT_TAKEOVER":
            console.log("[Background] 收到退出接管请求");
            sendResponse({ success: true });
            return true;
          case "TERMINATE_TASK":
            console.log("[Background] 收到终止任务请求");
            return handleAsyncMessage(
              () => __async(null, null, function* () {
                var _a4;
                const { getSessionManager: getSessionManager2 } = yield Promise.resolve().then(() => index$2);
                const { stopSession: stopSession2 } = yield Promise.resolve().then(() => sessionApi);
                const manager = getSessionManager2();
                const tabId = (_a4 = _sender.tab) == null ? void 0 : _a4.id;
                let sessionId = message.sessionId;
                if (!sessionId && tabId) {
                  const session = yield manager.getSessionByTabId(tabId);
                  sessionId = session == null ? void 0 : session.sessionId;
                }
                if (!sessionId) {
                  console.warn("[Background] TERMINATE_TASK: 无法获取 sessionId");
                  throw new Error("无法获取当前会话");
                }
                const apiSuccess = yield stopSession2(sessionId);
                if (!apiSuccess) {
                  console.error("[Background] 终止任务 API 调用失败");
                  throw new Error("终止任务请求失败");
                }
                yield manager.updateStatus(sessionId, "completed");
                console.log(`[Background] 任务已终止: ${sessionId}`);
                return { success: true, sessionId };
              }),
              sendResponse,
              3e4
              // 30秒超时
            );
          case "SUBMIT_TAKEOVER_INFO":
            console.log("[Background] 收到接管信息:", _sender, message.info);
            return handleAsyncMessage(
              () => __async(null, null, function* () {
                var _a4, _b3, _c2;
                const { getSessionManager: getSessionManager2 } = yield Promise.resolve().then(() => index$2);
                const { submitTakeoverMessage: submitTakeoverMessage2 } = yield Promise.resolve().then(() => sessionApi);
                const manager = getSessionManager2();
                const groupId = (_a4 = _sender.tab) == null ? void 0 : _a4.groupId;
                const tabId = (_b3 = _sender.tab) == null ? void 0 : _b3.id;
                let sessionId = message.sessionId;
                if (!sessionId && groupId) {
                  const session = yield manager.getSessionByGroupId(groupId);
                  sessionId = session == null ? void 0 : session.sessionId;
                }
                if (!sessionId && tabId) {
                  const session = yield manager.getSessionByTabId(tabId);
                  sessionId = session == null ? void 0 : session.sessionId;
                }
                if (!sessionId) {
                  console.warn("[Background] SUBMIT_TAKEOVER_INFO: 无法获取 sessionId");
                  throw new Error("无法获取当前会话");
                }
                if (!message.info) {
                  console.warn("[Background] SUBMIT_TAKEOVER_INFO: 缺少操作描述");
                  throw new Error("请输入操作描述");
                }
                const deviceStorage = yield chrome.storage.local.get("device_config");
                console.error("Background: 设备信息:", deviceStorage);
                const deviceId = (_c2 = deviceStorage.device_config) == null ? void 0 : _c2.deviceId;
                const apiSuccess = yield submitTakeoverMessage2(sessionId, {
                  deviceId,
                  messages: [
                    {
                      content: message.info,
                      role: "user"
                    }
                  ]
                });
                if (!apiSuccess) {
                  console.error("[Background] 提交接管信息 API 调用失败");
                  throw new Error("提交信息失败");
                }
                console.log(`[Background] 接管信息已提交: ${sessionId}`);
                return { success: true, sessionId };
              }),
              sendResponse,
              6e4
              // 60秒超时（接管提交可能耗时较长）
            );
        }
      }
    });
    chrome.runtime.onSuspend.addListener(() => {
      console.log("Background: 扩展即将卸载/重载，清理所有会话");
      cleanupChatAgent();
    });
    chrome.alarms.create("websocket_check", {
      delayInMinutes: 0.5,
      // 30秒后开始
      periodInMinutes: 0.5
      // 每30秒重复
    });
    chrome.alarms.create("update_capture_rules", {
      delayInMinutes: 60,
      // 1小时后开始
      periodInMinutes: 60
      // 每小时重复
    });
    chrome.alarms.onAlarm.addListener((alarm) => __async(null, null, function* () {
      if (alarm.name === "websocket_check") {
        const result2 = yield chrome.storage.local.get(["device_config"]);
        if (!result2.device_config) {
          return;
        }
        const status = getMCPStatus();
        if (!status.connected) {
          console.log("[WebSocket Monitor] 检测到连接断开，尝试重连...");
          try {
            yield initWebSocketMCPListener();
          } catch (error2) {
            console.error("[WebSocket Monitor] 重连失败:", error2);
          }
        }
      }
      if (alarm.name === "update_capture_rules") {
        console.log("[Background] 定期检查捕获规则更新...");
        try {
          yield updateCaptureRules({ respectTTL: true, silent: true });
          console.log("[Background] 捕获规则检查完成");
        } catch (error2) {
          console.error("[Background] 定期更新捕获规则失败:", error2);
        }
      }
    }));
    console.log("Background script initialized with WebSocket MCP support and simple monitoring");
  });
  function initPlugins() {
  }
  function print(method, ...args) {
    return;
  }
  const logger = {
    debug: (...args) => print(console.debug, ...args),
    log: (...args) => print(console.log, ...args),
    warn: (...args) => print(console.warn, ...args),
    error: (...args) => print(console.error, ...args)
  };
  let result;
  try {
    initPlugins();
    result = definition.main();
    if (result instanceof Promise) {
      console.warn(
        "The background's main() function return a promise, but it must be synchronous"
      );
    }
  } catch (err) {
    logger.error("The background crashed on startup!");
    throw err;
  }
  const result$1 = result;
  class TextChunker {
    constructor() {
      __publicField2(this, "defaultOptions", {
        maxWordsPerChunk: 80,
        overlapSentences: 1,
        minChunkLength: 20,
        includeTitle: true
      });
    }
    chunkText(content, title2, options) {
      const opts = __spreadValues(__spreadValues({}, this.defaultOptions), options);
      const chunks = [];
      if (opts.includeTitle && (title2 == null ? void 0 : title2.trim()) && title2.trim().length > 5) {
        chunks.push({
          text: title2.trim(),
          source: "title",
          index: 0,
          wordCount: title2.trim().split(/\s+/).length
        });
      }
      const cleanContent = content.trim();
      if (!cleanContent) {
        return chunks;
      }
      const sentences = this.splitIntoSentences(cleanContent);
      if (sentences.length === 0) {
        return this.fallbackChunking(cleanContent, chunks, opts);
      }
      const hasLongSentences = sentences.some(
        (s) => s.split(/\s+/).length > opts.maxWordsPerChunk
      );
      if (hasLongSentences) {
        return this.mixedChunking(sentences, chunks, opts);
      }
      return this.groupSentencesIntoChunks(sentences, chunks, opts);
    }
    splitIntoSentences(content) {
      const processedContent = content.replace(/([。！？])\s*/g, "$1\n").replace(/([.!?])\s+(?=[A-Z])/g, "$1\n").replace(/([.!?]["'])\s+(?=[A-Z])/g, "$1\n").replace(/([.!?])\s*$/gm, "$1\n").replace(/([。！？][""])\s*/g, "$1\n").replace(/\n\s*\n/g, "\n");
      const sentences = processedContent.split("\n").map((s) => s.trim()).filter((s) => s.length > 15);
      if (sentences.length < 3 && content.length > 500) {
        return this.aggressiveSentenceSplitting(content);
      }
      return sentences;
    }
    aggressiveSentenceSplitting(content) {
      const sentences = content.replace(/([.!?。！？])/g, "$1\n").replace(/([;；:：])/g, "$1\n").replace(/([)）])\s*(?=[\u4e00-\u9fa5A-Z])/g, "$1\n").split("\n").map((s) => s.trim()).filter((s) => s.length > 15);
      const maxWordsPerChunk = 80;
      const finalSentences = [];
      for (const sentence of sentences) {
        const words = sentence.split(/\s+/);
        if (words.length <= maxWordsPerChunk) {
          finalSentences.push(sentence);
        } else {
          const overlapWords = 5;
          for (let i2 = 0; i2 < words.length; i2 += maxWordsPerChunk - overlapWords) {
            const chunkWords = words.slice(i2, i2 + maxWordsPerChunk);
            const chunkText = chunkWords.join(" ");
            if (chunkText.length > 15) {
              finalSentences.push(chunkText);
            }
          }
        }
      }
      return finalSentences;
    }
    /**
     * Group sentences into chunks
     */
    groupSentencesIntoChunks(sentences, existingChunks, options) {
      const chunks = [...existingChunks];
      let chunkIndex = chunks.length;
      let i2 = 0;
      while (i2 < sentences.length) {
        let currentChunkText = "";
        let currentWordCount = 0;
        let sentencesUsed = 0;
        while (i2 + sentencesUsed < sentences.length && currentWordCount < options.maxWordsPerChunk) {
          const sentence = sentences[i2 + sentencesUsed];
          const sentenceWords = sentence.split(/\s+/).length;
          if (currentWordCount + sentenceWords > options.maxWordsPerChunk && currentWordCount > 0) {
            break;
          }
          currentChunkText += (currentChunkText ? " " : "") + sentence;
          currentWordCount += sentenceWords;
          sentencesUsed++;
        }
        if (currentChunkText.trim().length > options.minChunkLength) {
          chunks.push({
            text: currentChunkText.trim(),
            source: `content_chunk_${chunkIndex}`,
            index: chunkIndex,
            wordCount: currentWordCount
          });
          chunkIndex++;
        }
        i2 += Math.max(1, sentencesUsed - options.overlapSentences);
      }
      return chunks;
    }
    /**
     * Mixed chunking method (handles long sentences)
     */
    mixedChunking(sentences, existingChunks, options) {
      const chunks = [...existingChunks];
      let chunkIndex = chunks.length;
      for (const sentence of sentences) {
        const sentenceWords = sentence.split(/\s+/).length;
        if (sentenceWords <= options.maxWordsPerChunk) {
          chunks.push({
            text: sentence.trim(),
            source: `sentence_chunk_${chunkIndex}`,
            index: chunkIndex,
            wordCount: sentenceWords
          });
          chunkIndex++;
        } else {
          const words = sentence.split(/\s+/);
          for (let i2 = 0; i2 < words.length; i2 += options.maxWordsPerChunk) {
            const chunkWords = words.slice(i2, i2 + options.maxWordsPerChunk);
            const chunkText = chunkWords.join(" ");
            if (chunkText.length > options.minChunkLength) {
              chunks.push({
                text: chunkText,
                source: `long_sentence_chunk_${chunkIndex}_part_${Math.floor(i2 / options.maxWordsPerChunk)}`,
                index: chunkIndex,
                wordCount: chunkWords.length
              });
            }
          }
          chunkIndex++;
        }
      }
      return chunks;
    }
    /**
     * Fallback chunking (when sentence splitting fails)
     */
    fallbackChunking(content, existingChunks, options) {
      const chunks = [...existingChunks];
      let chunkIndex = chunks.length;
      const paragraphs = content.split(/\n\s*\n/).filter((p) => p.trim().length > options.minChunkLength);
      if (paragraphs.length > 1) {
        paragraphs.forEach((paragraph, index2) => {
          const cleanParagraph = paragraph.trim();
          if (cleanParagraph.length > 0) {
            const words = cleanParagraph.split(/\s+/);
            const maxWordsPerChunk = 150;
            for (let i2 = 0; i2 < words.length; i2 += maxWordsPerChunk) {
              const chunkWords = words.slice(i2, i2 + maxWordsPerChunk);
              const chunkText = chunkWords.join(" ");
              if (chunkText.length > options.minChunkLength) {
                chunks.push({
                  text: chunkText,
                  source: `paragraph_${index2}_chunk_${Math.floor(i2 / maxWordsPerChunk)}`,
                  index: chunkIndex,
                  wordCount: chunkWords.length
                });
                chunkIndex++;
              }
            }
          }
        });
      } else {
        const words = content.trim().split(/\s+/);
        const maxWordsPerChunk = 150;
        for (let i2 = 0; i2 < words.length; i2 += maxWordsPerChunk) {
          const chunkWords = words.slice(i2, i2 + maxWordsPerChunk);
          const chunkText = chunkWords.join(" ");
          if (chunkText.length > options.minChunkLength) {
            chunks.push({
              text: chunkText,
              source: `content_chunk_${Math.floor(i2 / maxWordsPerChunk)}`,
              index: chunkIndex,
              wordCount: chunkWords.length
            });
            chunkIndex++;
          }
        }
      }
      return chunks;
    }
  }
  let loadHnswlib, waitForFileSystemInitalized;
  (() => __async(null, null, function* () {
    let library;
    waitForFileSystemInitalized = () => {
      const EmscriptenFileSystemManager = library.EmscriptenFileSystemManager;
      return new Promise((resolve2, reject) => {
        let totalWaitTime = 0;
        const checkInterval = 100;
        const maxWaitTime = 4e3;
        const checkInitialization = () => {
          if (EmscriptenFileSystemManager.isInitialized()) {
            resolve2();
          } else if (totalWaitTime >= maxWaitTime) {
            reject(new Error("Failed to initialize filesystem"));
          } else {
            totalWaitTime += checkInterval;
            setTimeout(checkInitialization, checkInterval);
          }
        };
        setTimeout(checkInitialization, checkInterval);
      });
    };
    const initializeFileSystemAsync = (inputFsType) => __async(null, null, function* () {
      const fsType = inputFsType == null ? "IDBFS" : inputFsType;
      const EmscriptenFileSystemManager = library.EmscriptenFileSystemManager;
      if (EmscriptenFileSystemManager.isInitialized()) {
        return;
      }
      EmscriptenFileSystemManager.initializeFileSystem(fsType);
      return yield waitForFileSystemInitalized();
    });
    loadHnswlib = (inputFsType) => __async(null, null, function* () {
      try {
        if (typeof hnswlib !== "undefined" && hnswlib !== null) {
          const lib2 = hnswlib();
          if (lib2 != null)
            return lib2;
        }
        if (!library) {
          const temp = yield Promise.resolve().then(() => hnswlib210c0872);
          const factoryFunc = temp.default;
          library = yield factoryFunc();
          yield initializeFileSystemAsync(inputFsType);
          return library;
        }
        return library;
      } catch (err) {
        console.error("----------------------------------------");
        console.error("Error initializing the library:", err);
        throw err;
      }
    });
  }))();
  let globalHnswlib = null;
  let globalHnswlibInitPromise = null;
  let globalHnswlibInitialized = false;
  let syncInProgress = false;
  let pendingSyncPromise = null;
  const DB_NAME = "VectorDatabaseStorage";
  const DB_VERSION = 1;
  const STORE_NAME = "documentMappings";
  class IndexedDBHelper {
    static getDB() {
      return __async(this, null, function* () {
        if (!this.dbPromise) {
          this.dbPromise = new Promise((resolve2, reject) => {
            const request = indexedDB.open(DB_NAME, DB_VERSION);
            request.onerror = () => reject(request.error);
            request.onsuccess = () => resolve2(request.result);
            request.onupgradeneeded = (event) => {
              const db = event.target.result;
              if (!db.objectStoreNames.contains(STORE_NAME)) {
                const store = db.createObjectStore(STORE_NAME, { keyPath: "id" });
                store.createIndex("indexFileName", "indexFileName", { unique: false });
              }
            };
          });
        }
        return this.dbPromise;
      });
    }
    static saveData(indexFileName, data) {
      return __async(this, null, function* () {
        const db = yield this.getDB();
        const transaction = db.transaction([STORE_NAME], "readwrite");
        const store = transaction.objectStore(STORE_NAME);
        yield new Promise((resolve2, reject) => {
          const request = store.put({
            id: indexFileName,
            indexFileName,
            data,
            timestamp: Date.now()
          });
          request.onsuccess = () => resolve2();
          request.onerror = () => reject(request.error);
        });
      });
    }
    static loadData(indexFileName) {
      return __async(this, null, function* () {
        const db = yield this.getDB();
        const transaction = db.transaction([STORE_NAME], "readonly");
        const store = transaction.objectStore(STORE_NAME);
        return new Promise((resolve2, reject) => {
          const request = store.get(indexFileName);
          request.onsuccess = () => {
            const result2 = request.result;
            resolve2(result2 ? result2.data : null);
          };
          request.onerror = () => reject(request.error);
        });
      });
    }
    static deleteData(indexFileName) {
      return __async(this, null, function* () {
        const db = yield this.getDB();
        const transaction = db.transaction([STORE_NAME], "readwrite");
        const store = transaction.objectStore(STORE_NAME);
        yield new Promise((resolve2, reject) => {
          const request = store.delete(indexFileName);
          request.onsuccess = () => resolve2();
          request.onerror = () => reject(request.error);
        });
      });
    }
    /**
     * Clear all IndexedDB data (for complete cleanup during model switching)
     */
    static clearAllData() {
      return __async(this, null, function* () {
        try {
          const db = yield this.getDB();
          const transaction = db.transaction([STORE_NAME], "readwrite");
          const store = transaction.objectStore(STORE_NAME);
          yield new Promise((resolve2, reject) => {
            const request = store.clear();
            request.onsuccess = () => {
              console.log("IndexedDBHelper: All data cleared from IndexedDB");
              resolve2();
            };
            request.onerror = () => reject(request.error);
          });
        } catch (error2) {
          console.error("IndexedDBHelper: Failed to clear all data:", error2);
          throw error2;
        }
      });
    }
    /**
     * Get all stored keys (for debugging)
     */
    static getAllKeys() {
      return __async(this, null, function* () {
        try {
          const db = yield this.getDB();
          const transaction = db.transaction([STORE_NAME], "readonly");
          const store = transaction.objectStore(STORE_NAME);
          return new Promise((resolve2, reject) => {
            const request = store.getAllKeys();
            request.onsuccess = () => resolve2(request.result);
            request.onerror = () => reject(request.error);
          });
        } catch (error2) {
          console.error("IndexedDBHelper: Failed to get all keys:", error2);
          return [];
        }
      });
    }
  }
  __publicField2(IndexedDBHelper, "dbPromise", null);
  function initializeGlobalHnswlib() {
    return __async(this, null, function* () {
      if (globalHnswlibInitialized && globalHnswlib) {
        return globalHnswlib;
      }
      if (globalHnswlibInitPromise) {
        return globalHnswlibInitPromise;
      }
      globalHnswlibInitPromise = (() => __async(null, null, function* () {
        try {
          console.log("VectorDatabase: Initializing global hnswlib-wasm instance...");
          globalHnswlib = yield loadHnswlib();
          globalHnswlibInitialized = true;
          console.log("VectorDatabase: Global hnswlib-wasm instance initialized successfully");
          return globalHnswlib;
        } catch (error2) {
          console.error("VectorDatabase: Failed to initialize global hnswlib-wasm:", error2);
          globalHnswlibInitPromise = null;
          throw error2;
        }
      }))();
      return globalHnswlibInitPromise;
    });
  }
  class VectorDatabase {
    constructor(config2) {
      __publicField2(this, "index", null);
      __publicField2(this, "isInitialized", false);
      __publicField2(this, "isInitializing", false);
      __publicField2(this, "initPromise", null);
      __publicField2(this, "documents", /* @__PURE__ */ new Map());
      __publicField2(this, "tabDocuments", /* @__PURE__ */ new Map());
      __publicField2(this, "nextLabel", 0);
      __publicField2(this, "config");
      this.config = __spreadValues({
        dimension: 384,
        maxElements: 1e5,
        efConstruction: 200,
        M: 48,
        efSearch: 50,
        indexFileName: "tab_content_index.dat",
        enableAutoCleanup: true,
        maxRetentionDays: 30
      }, config2);
      console.log("VectorDatabase: Initialized with config:", {
        dimension: this.config.dimension,
        efSearch: this.config.efSearch,
        M: this.config.M,
        efConstruction: this.config.efConstruction,
        enableAutoCleanup: this.config.enableAutoCleanup,
        maxRetentionDays: this.config.maxRetentionDays
      });
    }
    /**
     * Initialize vector database
     */
    initialize() {
      return __async(this, null, function* () {
        if (this.isInitialized) return;
        if (this.isInitializing && this.initPromise) return this.initPromise;
        this.isInitializing = true;
        this.initPromise = this._doInitialize().finally(() => {
          this.isInitializing = false;
        });
        return this.initPromise;
      });
    }
    _doInitialize() {
      return __async(this, null, function* () {
        try {
          console.log("VectorDatabase: Initializing...");
          const hnswlib2 = yield initializeGlobalHnswlib();
          hnswlib2.EmscriptenFileSystemManager.setDebugLogs(true);
          this.index = new hnswlib2.HierarchicalNSW(
            "cosine",
            this.config.dimension,
            this.config.indexFileName
          );
          yield this.syncFileSystem("read");
          const indexExists = hnswlib2.EmscriptenFileSystemManager.checkFileExists(
            this.config.indexFileName
          );
          if (indexExists) {
            console.log("VectorDatabase: Loading existing index...");
            try {
              yield this.index.readIndex(this.config.indexFileName, this.config.maxElements);
              this.index.setEfSearch(this.config.efSearch);
              yield this.loadDocumentMappings();
              if (this.documents.size > 0) {
                const maxLabel = Math.max(...Array.from(this.documents.keys()));
                this.nextLabel = maxLabel + 1;
                console.log(
                  `VectorDatabase: Loaded existing index with ${this.documents.size} documents, next label: ${this.nextLabel}`
                );
              } else {
                const indexCount = this.index.getCurrentCount();
                if (indexCount > 0) {
                  console.warn(
                    `VectorDatabase: Index has ${indexCount} vectors but no document mappings found. This may cause label mismatch.`
                  );
                  this.nextLabel = indexCount;
                } else {
                  this.nextLabel = 0;
                }
                console.log(
                  `VectorDatabase: No document mappings found, starting with next label: ${this.nextLabel}`
                );
              }
            } catch (loadError) {
              console.warn(
                "VectorDatabase: Failed to load existing index, creating new one:",
                loadError
              );
              this.index.initIndex(
                this.config.maxElements,
                this.config.M,
                this.config.efConstruction,
                200
              );
              this.index.setEfSearch(this.config.efSearch);
              this.nextLabel = 0;
            }
          } else {
            console.log("VectorDatabase: Creating new index...");
            this.index.initIndex(
              this.config.maxElements,
              this.config.M,
              this.config.efConstruction,
              200
            );
            this.index.setEfSearch(this.config.efSearch);
            this.nextLabel = 0;
          }
          this.isInitialized = true;
          console.log("VectorDatabase: Initialization completed successfully");
        } catch (error2) {
          console.error("VectorDatabase: Initialization failed:", error2);
          this.isInitialized = false;
          throw error2;
        }
      });
    }
    /**
     * Add document to vector database
     */
    addDocument(tabId, url2, title2, chunk, embedding) {
      return __async(this, null, function* () {
        var _a3;
        if (!this.isInitialized) {
          yield this.initialize();
        }
        const documentId = this.generateDocumentId(tabId, chunk.index);
        const document2 = {
          id: documentId,
          tabId,
          url: url2,
          title: title2,
          chunk,
          embedding,
          timestamp: Date.now()
        };
        try {
          if (!embedding || embedding.length !== this.config.dimension) {
            const errorMsg = `Invalid embedding dimension: expected ${this.config.dimension}, got ${(embedding == null ? void 0 : embedding.length) || 0}`;
            console.error("VectorDatabase: Dimension mismatch detected!", {
              expectedDimension: this.config.dimension,
              actualDimension: (embedding == null ? void 0 : embedding.length) || 0,
              documentId,
              tabId,
              url: url2,
              title: title2.substring(0, 50) + "..."
            });
            console.warn(
              "VectorDatabase: This might be caused by model switching. Consider reinitializing the vector database with the correct dimension."
            );
            throw new Error(errorMsg);
          }
          for (let i2 = 0; i2 < embedding.length; i2++) {
            if (!isFinite(embedding[i2])) {
              throw new Error(`Invalid embedding value at index ${i2}: ${embedding[i2]}`);
            }
          }
          let cleanEmbedding;
          if (embedding instanceof Float32Array) {
            cleanEmbedding = embedding;
          } else {
            cleanEmbedding = new Float32Array(embedding);
          }
          const label = this.nextLabel++;
          console.log(
            `VectorDatabase: Adding document with label ${label}, embedding dimension: ${embedding.length}`
          );
          console.log(`VectorDatabase: 🔧 DEBUGGING - About to call addPoint with:`, {
            embeddingType: typeof cleanEmbedding,
            isFloat32Array: cleanEmbedding instanceof Float32Array,
            length: cleanEmbedding.length,
            firstFewValues: Array.from(cleanEmbedding.slice(0, 3)),
            label,
            replaceDeleted: false
          });
          let vectorToAdd;
          try {
            if (globalHnswlib && globalHnswlib.VectorFloat) {
              console.log("VectorDatabase: Using VectorFloat constructor");
              vectorToAdd = new globalHnswlib.VectorFloat();
              for (let i2 = 0; i2 < cleanEmbedding.length; i2++) {
                vectorToAdd.push_back(cleanEmbedding[i2]);
              }
            } else {
              console.log("VectorDatabase: Using plain JS array as fallback");
              vectorToAdd = Array.from(cleanEmbedding);
            }
            this.index.addPoint(vectorToAdd, label, false);
            if (vectorToAdd && typeof vectorToAdd.delete === "function") {
              vectorToAdd.delete();
            }
          } catch (vectorError) {
            console.error(
              "VectorDatabase: VectorFloat approach failed, trying alternatives:",
              vectorError
            );
            try {
              console.log("VectorDatabase: Trying Float32Array directly");
              this.index.addPoint(cleanEmbedding, label, false);
            } catch (float32Error) {
              console.error("VectorDatabase: Float32Array approach failed:", float32Error);
              console.log("VectorDatabase: Trying spread operator as last resort");
              this.index.addPoint([...cleanEmbedding], label, false);
            }
          }
          console.log(`VectorDatabase: ✅ Successfully added document with label ${label}`);
          this.documents.set(label, document2);
          if (!this.tabDocuments.has(tabId)) {
            this.tabDocuments.set(tabId, /* @__PURE__ */ new Set());
          }
          this.tabDocuments.get(tabId).add(label);
          yield this.saveIndex();
          yield this.saveDocumentMappings();
          if (this.config.enableAutoCleanup) {
            yield this.checkAndPerformAutoCleanup();
          }
          console.log(`VectorDatabase: Successfully added document ${documentId} with label ${label}`);
          return label;
        } catch (error2) {
          console.error("VectorDatabase: Failed to add document:", error2);
          console.error("VectorDatabase: Embedding info:", {
            type: typeof embedding,
            constructor: (_a3 = embedding == null ? void 0 : embedding.constructor) == null ? void 0 : _a3.name,
            length: embedding == null ? void 0 : embedding.length,
            isFloat32Array: embedding instanceof Float32Array,
            firstFewValues: embedding ? Array.from(embedding.slice(0, 5)) : null
          });
          throw error2;
        }
      });
    }
    /**
     * Search similar documents
     */
    search(queryEmbedding, topK = 10) {
      return __async(this, null, function* () {
        var _a3;
        if (!this.isInitialized) {
          yield this.initialize();
        }
        try {
          if (!queryEmbedding || queryEmbedding.length !== this.config.dimension) {
            throw new Error(
              `Invalid query embedding dimension: expected ${this.config.dimension}, got ${(queryEmbedding == null ? void 0 : queryEmbedding.length) || 0}`
            );
          }
          for (let i2 = 0; i2 < queryEmbedding.length; i2++) {
            if (!isFinite(queryEmbedding[i2])) {
              throw new Error(`Invalid query embedding value at index ${i2}: ${queryEmbedding[i2]}`);
            }
          }
          console.log(
            `VectorDatabase: Searching with query embedding dimension: ${queryEmbedding.length}, topK: ${topK}`
          );
          const currentCount = this.index.getCurrentCount();
          if (currentCount === 0) {
            console.log("VectorDatabase: Index is empty, returning no results");
            return [];
          }
          console.log(`VectorDatabase: Index contains ${currentCount} vectors`);
          const mappingCount = this.documents.size;
          if (mappingCount === 0 && currentCount > 0) {
            console.warn(
              `VectorDatabase: Index has ${currentCount} vectors but document mapping is empty. Attempting to reload mappings...`
            );
            yield this.loadDocumentMappings();
            if (this.documents.size === 0) {
              console.error(
                "VectorDatabase: Failed to load document mappings. Index and mappings are out of sync."
              );
              return [];
            }
            console.log(
              `VectorDatabase: Successfully reloaded ${this.documents.size} document mappings`
            );
          }
          let queryVector;
          let searchResult;
          try {
            if (globalHnswlib && globalHnswlib.VectorFloat) {
              console.log("VectorDatabase: Using VectorFloat for search query");
              queryVector = new globalHnswlib.VectorFloat();
              for (let i2 = 0; i2 < queryEmbedding.length; i2++) {
                queryVector.push_back(queryEmbedding[i2]);
              }
              searchResult = this.index.searchKnn(queryVector, topK, void 0);
              if (queryVector && typeof queryVector.delete === "function") {
                queryVector.delete();
              }
            } else {
              console.log("VectorDatabase: Using plain JS array for search query");
              const queryArray = Array.from(queryEmbedding);
              searchResult = this.index.searchKnn(queryArray, topK, void 0);
            }
          } catch (vectorError) {
            console.error(
              "VectorDatabase: VectorFloat search failed, trying alternatives:",
              vectorError
            );
            try {
              console.log("VectorDatabase: Trying Float32Array directly for search");
              searchResult = this.index.searchKnn(queryEmbedding, topK, void 0);
            } catch (float32Error) {
              console.error("VectorDatabase: Float32Array search failed:", float32Error);
              console.log("VectorDatabase: Trying spread operator for search as last resort");
              searchResult = this.index.searchKnn([...queryEmbedding], topK, void 0);
            }
          }
          const results = [];
          console.log(`VectorDatabase: Processing ${searchResult.neighbors.length} search neighbors`);
          console.log(`VectorDatabase: Available documents in mapping: ${this.documents.size}`);
          console.log(`VectorDatabase: Index current count: ${this.index.getCurrentCount()}`);
          for (let i2 = 0; i2 < searchResult.neighbors.length; i2++) {
            const label = searchResult.neighbors[i2];
            const distance = searchResult.distances[i2];
            const similarity = 1 - distance;
            console.log(
              `VectorDatabase: Processing neighbor ${i2}: label=${label}, distance=${distance}, similarity=${similarity}`
            );
            const document2 = this.findDocumentByLabel(label);
            if (document2) {
              console.log(`VectorDatabase: Found document for label ${label}: ${document2.id}`);
              results.push({
                document: document2,
                similarity,
                distance
              });
            } else {
              console.warn(`VectorDatabase: No document found for label ${label}`);
              if (i2 < 5) {
                console.warn(
                  `VectorDatabase: Available labels (first 20): ${Array.from(this.documents.keys()).slice(0, 20).join(", ")}`
                );
                console.warn(`VectorDatabase: Total available labels: ${this.documents.size}`);
                console.warn(
                  `VectorDatabase: Label type: ${typeof label}, Available label types: ${Array.from(
                    this.documents.keys()
                  ).slice(0, 3).map((k) => typeof k).join(", ")}`
                );
              }
            }
          }
          console.log(
            `VectorDatabase: Found ${results.length} search results out of ${searchResult.neighbors.length} neighbors`
          );
          if (results.length === 0 && searchResult.neighbors.length > 0) {
            console.error(
              "VectorDatabase: Label mismatch detected! Index has vectors but no matching documents found."
            );
            console.error(
              "VectorDatabase: This usually indicates the index and document mappings are out of sync."
            );
            console.error("VectorDatabase: Consider rebuilding the index to fix this issue.");
            const sampleLabels = searchResult.neighbors.slice(0, 5);
            const availableLabels = Array.from(this.documents.keys()).slice(0, 5);
            console.error("VectorDatabase: Sample search labels:", sampleLabels);
            console.error("VectorDatabase: Sample available labels:", availableLabels);
          }
          return results.sort((a, b) => b.similarity - a.similarity);
        } catch (error2) {
          console.error("VectorDatabase: Search failed:", error2);
          console.error("VectorDatabase: Query embedding info:", {
            type: typeof queryEmbedding,
            constructor: (_a3 = queryEmbedding == null ? void 0 : queryEmbedding.constructor) == null ? void 0 : _a3.name,
            length: queryEmbedding == null ? void 0 : queryEmbedding.length,
            isFloat32Array: queryEmbedding instanceof Float32Array,
            firstFewValues: queryEmbedding ? Array.from(queryEmbedding.slice(0, 5)) : null
          });
          throw error2;
        }
      });
    }
    /**
     * Remove all documents for a tab
     */
    removeTabDocuments(tabId) {
      return __async(this, null, function* () {
        if (!this.isInitialized) {
          yield this.initialize();
        }
        const documentLabels = this.tabDocuments.get(tabId);
        if (!documentLabels) {
          return;
        }
        try {
          for (const label of documentLabels) {
            this.documents.delete(label);
          }
          this.tabDocuments.delete(tabId);
          yield this.saveDocumentMappings();
          console.log(`VectorDatabase: Removed ${documentLabels.size} documents for tab ${tabId}`);
        } catch (error2) {
          console.error("VectorDatabase: Failed to remove tab documents:", error2);
          throw error2;
        }
      });
    }
    /**
     * Get database statistics
     */
    getStats() {
      return {
        totalDocuments: this.documents.size,
        totalTabs: this.tabDocuments.size,
        indexSize: this.calculateStorageSize(),
        isInitialized: this.isInitialized
      };
    }
    /**
     * Calculate actual storage size (bytes)
     */
    calculateStorageSize() {
      let totalSize = 0;
      try {
        const documentsSize = this.calculateDocumentMappingsSize();
        totalSize += documentsSize;
        const vectorsSize = this.calculateVectorsSize();
        totalSize += vectorsSize;
        const indexStructureSize = this.calculateIndexStructureSize();
        totalSize += indexStructureSize;
        console.log(
          `VectorDatabase: Storage size breakdown - Documents: ${documentsSize}, Vectors: ${vectorsSize}, Index: ${indexStructureSize}, Total: ${totalSize} bytes`
        );
      } catch (error2) {
        console.warn("VectorDatabase: Failed to calculate storage size:", error2);
        totalSize = this.documents.size * 1024;
      }
      return totalSize;
    }
    /**
     * Calculate document mappings size
     */
    calculateDocumentMappingsSize() {
      let size = 0;
      for (const [label, document2] of this.documents.entries()) {
        size += 8;
        size += this.calculateObjectSize(document2);
      }
      for (const [tabId, labels] of this.tabDocuments.entries()) {
        size += 8;
        size += labels.size * 8 + 32;
      }
      return size;
    }
    /**
     * Calculate vectors data size
     */
    calculateVectorsSize() {
      const documentCount = this.documents.size;
      const dimension = this.config.dimension;
      const vectorSize = dimension * 4;
      return documentCount * vectorSize;
    }
    /**
     * Estimate index structure size
     */
    calculateIndexStructureSize() {
      const documentCount = this.documents.size;
      if (documentCount === 0) return 0;
      const vectorsSize = this.calculateVectorsSize();
      const indexOverhead = Math.floor(vectorsSize * 0.3);
      const graphOverhead = documentCount * 64;
      return indexOverhead + graphOverhead;
    }
    /**
     * Calculate object size (rough estimation)
     */
    calculateObjectSize(obj) {
      let size = 0;
      try {
        const jsonString = JSON.stringify(obj);
        size = jsonString.length * 2;
      } catch (error2) {
        size = 512;
      }
      return size;
    }
    /**
     * Clear entire database
     */
    clear() {
      return __async(this, null, function* () {
        console.log("VectorDatabase: Starting complete database clear...");
        try {
          this.documents.clear();
          this.tabDocuments.clear();
          this.nextLabel = 0;
          if (this.isInitialized && this.index) {
            try {
              console.log("VectorDatabase: Clearing HNSW index file from IndexedDB...");
              try {
                if (globalHnswlib && globalHnswlib.EmscriptenFileSystemManager.checkFileExists(this.config.indexFileName)) {
                  console.log(
                    `VectorDatabase: Deleting physical index file: ${this.config.indexFileName}`
                  );
                  globalHnswlib.EmscriptenFileSystemManager.deleteFile(this.config.indexFileName);
                  yield this.syncFileSystem("write");
                  console.log(
                    `VectorDatabase: Physical index file ${this.config.indexFileName} deleted successfully`
                  );
                } else {
                  console.log(
                    `VectorDatabase: Physical index file ${this.config.indexFileName} does not exist or already deleted`
                  );
                }
              } catch (fileError) {
                console.warn(
                  `VectorDatabase: Failed to delete physical index file ${this.config.indexFileName}:`,
                  fileError
                );
              }
              yield this.index.deleteIndex(this.config.indexFileName);
              console.log("VectorDatabase: HNSW index file cleared from IndexedDB");
              console.log("VectorDatabase: Reinitializing empty HNSW index...");
              this.index.initIndex(
                this.config.maxElements,
                this.config.M,
                this.config.efConstruction,
                200
              );
              this.index.setEfSearch(this.config.efSearch);
              yield this.forceSaveIndex();
            } catch (indexError) {
              console.warn("VectorDatabase: Failed to clear HNSW index file:", indexError);
            }
          }
          try {
            console.log("VectorDatabase: Clearing document mappings from IndexedDB...");
            yield IndexedDBHelper.deleteData(this.config.indexFileName);
            console.log("VectorDatabase: Document mappings cleared from IndexedDB");
          } catch (idbError) {
            console.warn(
              "VectorDatabase: Failed to clear document mappings from IndexedDB, trying chrome.storage fallback:",
              idbError
            );
            try {
              const storageKey = `hnswlib_document_mappings_${this.config.indexFileName}`;
              yield chrome.storage.local.remove([storageKey]);
              console.log("VectorDatabase: Chrome storage fallback cleared");
            } catch (storageError) {
              console.warn("VectorDatabase: Failed to clear chrome.storage fallback:", storageError);
            }
          }
          yield this.saveDocumentMappings();
          console.log("VectorDatabase: Complete database clear finished successfully");
        } catch (error2) {
          console.error("VectorDatabase: Failed to clear database:", error2);
          throw error2;
        }
      });
    }
    /**
     * Force save index and sync filesystem
     */
    forceSaveIndex() {
      return __async(this, null, function* () {
        try {
          yield this.index.writeIndex(this.config.indexFileName);
          yield this.syncFileSystem("write");
        } catch (error2) {
          console.error("VectorDatabase: Failed to force save index:", error2);
        }
      });
    }
    /**
     * Check and perform auto cleanup
     */
    checkAndPerformAutoCleanup() {
      return __async(this, null, function* () {
        try {
          const currentCount = this.documents.size;
          const maxElements = this.config.maxElements;
          console.log(
            `VectorDatabase: Auto cleanup check - current: ${currentCount}, max: ${maxElements}`
          );
          if (currentCount >= maxElements) {
            console.log("VectorDatabase: Document count reached limit, performing cleanup...");
            yield this.performLRUCleanup(Math.floor(maxElements * 0.2));
          }
          if (this.config.maxRetentionDays && this.config.maxRetentionDays > 0) {
            yield this.performTimeBasedCleanup();
          }
        } catch (error2) {
          console.error("VectorDatabase: Auto cleanup failed:", error2);
        }
      });
    }
    /**
     * Perform LRU-based cleanup (delete oldest documents)
     */
    performLRUCleanup(cleanupCount) {
      return __async(this, null, function* () {
        try {
          console.log(
            `VectorDatabase: Starting LRU cleanup, removing ${cleanupCount} oldest documents`
          );
          const allDocuments = Array.from(this.documents.entries());
          allDocuments.sort((a, b) => a[1].timestamp - b[1].timestamp);
          const documentsToDelete = allDocuments.slice(0, cleanupCount);
          for (const [label, _document] of documentsToDelete) {
            yield this.removeDocumentByLabel(label);
          }
          yield this.saveIndex();
          yield this.saveDocumentMappings();
          console.log(
            `VectorDatabase: LRU cleanup completed, removed ${documentsToDelete.length} documents`
          );
        } catch (error2) {
          console.error("VectorDatabase: LRU cleanup failed:", error2);
        }
      });
    }
    /**
     * Perform time-based cleanup (delete expired documents)
     */
    performTimeBasedCleanup() {
      return __async(this, null, function* () {
        try {
          const maxRetentionMs = this.config.maxRetentionDays * 24 * 60 * 60 * 1e3;
          const cutoffTime = Date.now() - maxRetentionMs;
          console.log(
            `VectorDatabase: Starting time-based cleanup, removing documents older than ${this.config.maxRetentionDays} days`
          );
          const documentsToDelete = [];
          for (const [label, document2] of this.documents.entries()) {
            if (document2.timestamp < cutoffTime) {
              documentsToDelete.push(label);
            }
          }
          for (const label of documentsToDelete) {
            yield this.removeDocumentByLabel(label);
          }
          if (documentsToDelete.length > 0) {
            yield this.saveIndex();
            yield this.saveDocumentMappings();
          }
          console.log(
            `VectorDatabase: Time-based cleanup completed, removed ${documentsToDelete.length} expired documents`
          );
        } catch (error2) {
          console.error("VectorDatabase: Time-based cleanup failed:", error2);
        }
      });
    }
    /**
     * Remove single document by label
     */
    removeDocumentByLabel(label) {
      return __async(this, null, function* () {
        try {
          const document2 = this.documents.get(label);
          if (!document2) {
            console.warn(`VectorDatabase: Document with label ${label} not found`);
            return;
          }
          if (this.index) {
            try {
              this.index.markDelete(label);
            } catch (indexError) {
              console.warn(
                `VectorDatabase: Failed to mark delete in index for label ${label}:`,
                indexError
              );
            }
          }
          this.documents.delete(label);
          const tabId = document2.tabId;
          if (this.tabDocuments.has(tabId)) {
            this.tabDocuments.get(tabId).delete(label);
            if (this.tabDocuments.get(tabId).size === 0) {
              this.tabDocuments.delete(tabId);
            }
          }
          console.log(`VectorDatabase: Removed document with label ${label} from tab ${tabId}`);
        } catch (error2) {
          console.error(`VectorDatabase: Failed to remove document with label ${label}:`, error2);
        }
      });
    }
    // 私有辅助方法
    generateDocumentId(tabId, chunkIndex) {
      return `tab_${tabId}_chunk_${chunkIndex}_${Date.now()}`;
    }
    findDocumentByLabel(label) {
      return this.documents.get(label) || null;
    }
    syncFileSystem(direction) {
      return __async(this, null, function* () {
        try {
          if (!globalHnswlib) {
            return;
          }
          if (syncInProgress && pendingSyncPromise) {
            console.log(`VectorDatabase: Sync already in progress, waiting...`);
            yield pendingSyncPromise;
            return;
          }
          syncInProgress = true;
          pendingSyncPromise = new Promise((resolve2, reject) => {
            const timeout = setTimeout(() => {
              console.warn(`VectorDatabase: Filesystem sync (${direction}) timeout`);
              syncInProgress = false;
              pendingSyncPromise = null;
              reject(new Error("Sync timeout"));
            }, 5e3);
            try {
              globalHnswlib.EmscriptenFileSystemManager.syncFS(direction === "read", () => {
                clearTimeout(timeout);
                console.log(`VectorDatabase: Filesystem sync (${direction}) completed`);
                syncInProgress = false;
                pendingSyncPromise = null;
                resolve2();
              });
            } catch (error2) {
              clearTimeout(timeout);
              console.warn(`VectorDatabase: Failed to sync filesystem (${direction}):`, error2);
              syncInProgress = false;
              pendingSyncPromise = null;
              reject(error2);
            }
          });
          yield pendingSyncPromise;
        } catch (error2) {
          console.warn(`VectorDatabase: Failed to sync filesystem (${direction}):`, error2);
          syncInProgress = false;
          pendingSyncPromise = null;
        }
      });
    }
    saveIndex() {
      return __async(this, null, function* () {
        try {
          yield this.index.writeIndex(this.config.indexFileName);
          if (this.documents.size % 10 === 0) {
            yield this.syncFileSystem("write");
          }
        } catch (error2) {
          console.error("VectorDatabase: Failed to save index:", error2);
        }
      });
    }
    saveDocumentMappings() {
      return __async(this, null, function* () {
        try {
          const mappingData = {
            documents: Array.from(this.documents.entries()),
            tabDocuments: Array.from(this.tabDocuments.entries()).map(([tabId, labels]) => [
              tabId,
              Array.from(labels)
            ]),
            nextLabel: this.nextLabel
          };
          try {
            yield IndexedDBHelper.saveData(this.config.indexFileName, mappingData);
            console.log("VectorDatabase: Document mappings saved to IndexedDB");
          } catch (idbError) {
            console.warn(
              "VectorDatabase: Failed to save to IndexedDB, falling back to chrome.storage:",
              idbError
            );
            try {
              const storageKey = `hnswlib_document_mappings_${this.config.indexFileName}`;
              yield chrome.storage.local.set({ [storageKey]: mappingData });
              console.log("VectorDatabase: Document mappings saved to chrome.storage.local (fallback)");
            } catch (storageError) {
              console.error(
                "VectorDatabase: Failed to save to both IndexedDB and chrome.storage:",
                storageError
              );
            }
          }
        } catch (error2) {
          console.error("VectorDatabase: Failed to save document mappings:", error2);
        }
      });
    }
    loadDocumentMappings() {
      return __async(this, null, function* () {
        try {
          if (!globalHnswlib) {
            return;
          }
          let mappingData = null;
          try {
            mappingData = yield IndexedDBHelper.loadData(this.config.indexFileName);
            if (mappingData) {
              console.log(`VectorDatabase: Loaded document mappings from IndexedDB`);
            }
          } catch (idbError) {
            console.warn(
              "VectorDatabase: Failed to read from IndexedDB, trying chrome.storage:",
              idbError
            );
          }
          if (!mappingData) {
            try {
              const storageKey = `hnswlib_document_mappings_${this.config.indexFileName}`;
              const result2 = yield chrome.storage.local.get([storageKey]);
              mappingData = result2[storageKey];
              if (mappingData) {
                console.log(
                  `VectorDatabase: Loaded document mappings from chrome.storage.local (fallback)`
                );
                try {
                  yield IndexedDBHelper.saveData(this.config.indexFileName, mappingData);
                  console.log("VectorDatabase: Migrated data from chrome.storage to IndexedDB");
                } catch (migrationError) {
                  console.warn("VectorDatabase: Failed to migrate data to IndexedDB:", migrationError);
                }
              }
            } catch (storageError) {
              console.warn("VectorDatabase: Failed to read from chrome.storage.local:", storageError);
            }
          }
          if (mappingData) {
            this.documents.clear();
            for (const [label, doc] of mappingData.documents) {
              this.documents.set(label, doc);
            }
            this.tabDocuments.clear();
            for (const [tabId, labels] of mappingData.tabDocuments) {
              this.tabDocuments.set(tabId, new Set(labels));
            }
            if (mappingData.nextLabel !== void 0) {
              this.nextLabel = mappingData.nextLabel;
            } else if (this.documents.size > 0) {
              const maxLabel = Math.max(...Array.from(this.documents.keys()));
              this.nextLabel = maxLabel + 1;
            } else {
              this.nextLabel = 0;
            }
            console.log(
              `VectorDatabase: Loaded ${this.documents.size} document mappings, next label: ${this.nextLabel}`
            );
          } else {
            console.log("VectorDatabase: No existing document mappings found");
          }
        } catch (error2) {
          console.error("VectorDatabase: Failed to load document mappings:", error2);
        }
      });
    }
  }
  let globalVectorDatabase = null;
  let currentDimension = null;
  function getGlobalVectorDatabase(config2) {
    return __async(this, null, function* () {
      const newDimension = (config2 == null ? void 0 : config2.dimension) || 384;
      if (globalVectorDatabase && currentDimension !== null && currentDimension !== newDimension) {
        console.log(
          `VectorDatabase: Dimension changed from ${currentDimension} to ${newDimension}, recreating instance`
        );
        try {
          yield globalVectorDatabase.clear();
          console.log("VectorDatabase: Successfully cleared old instance for dimension change");
        } catch (error2) {
          console.warn("VectorDatabase: Error during cleanup:", error2);
        }
        globalVectorDatabase = null;
        currentDimension = null;
      }
      if (!globalVectorDatabase) {
        globalVectorDatabase = new VectorDatabase(config2);
        currentDimension = newDimension;
        console.log(
          `VectorDatabase: Created global singleton instance with dimension ${currentDimension}`
        );
      }
      return globalVectorDatabase;
    });
  }
  function clearAllVectorData() {
    return __async(this, null, function* () {
      console.log("VectorDatabase: Starting comprehensive vector data cleanup for model switch...");
      try {
        if (globalVectorDatabase) {
          try {
            yield globalVectorDatabase.clear();
          } catch (error2) {
            console.warn("VectorDatabase: Failed to clear global instance:", error2);
          }
        }
        try {
          console.log("VectorDatabase: Clearing VectorDatabaseStorage database...");
          yield IndexedDBHelper.clearAllData();
        } catch (error2) {
          console.warn("VectorDatabase: Failed to clear VectorDatabaseStorage:", error2);
        }
        try {
          console.log("VectorDatabase: Clearing hnswlib-index database and physical files...");
          if (typeof globalHnswlib !== "undefined" && globalHnswlib) {
            const possibleIndexFiles = [
              "tab_content_index.dat",
              "content_index.dat",
              "vector_index.dat"
            ];
            for (const fileName of possibleIndexFiles) {
              try {
                if (globalHnswlib.EmscriptenFileSystemManager.checkFileExists(fileName)) {
                  console.log(`VectorDatabase: Deleting physical index file: ${fileName}`);
                  globalHnswlib.EmscriptenFileSystemManager.deleteFile(fileName);
                  console.log(`VectorDatabase: Physical index file ${fileName} deleted successfully`);
                }
              } catch (fileError) {
                console.log(
                  `VectorDatabase: Physical index file ${fileName} not found or failed to delete:`,
                  fileError
                );
              }
            }
            try {
              yield new Promise((resolve2) => {
                const timeout = setTimeout(() => {
                  console.warn("VectorDatabase: Filesystem sync timeout during model switch cleanup");
                  resolve2();
                }, 3e3);
                globalHnswlib.EmscriptenFileSystemManager.syncFS(false, () => {
                  clearTimeout(timeout);
                  console.log("VectorDatabase: Filesystem sync completed during model switch cleanup");
                  resolve2();
                });
              });
            } catch (syncError) {
              console.warn(
                "VectorDatabase: Failed to sync filesystem during model switch cleanup:",
                syncError
              );
            }
          }
          yield new Promise((resolve2) => {
            const deleteRequest = indexedDB.deleteDatabase("/hnswlib-index");
            deleteRequest.onsuccess = () => {
              console.log("VectorDatabase: Successfully deleted /hnswlib-index database");
              resolve2();
            };
            deleteRequest.onerror = () => {
              console.warn(
                "VectorDatabase: Failed to delete /hnswlib-index database:",
                deleteRequest.error
              );
              resolve2();
            };
            deleteRequest.onblocked = () => {
              console.warn("VectorDatabase: Deletion of /hnswlib-index database was blocked");
              resolve2();
            };
          });
        } catch (error2) {
          console.warn(
            "VectorDatabase: Failed to clear hnswlib-index database and physical files:",
            error2
          );
        }
        try {
          const storageKeys = [
            "hnswlib_document_mappings_tab_content_index.dat",
            "hnswlib_document_mappings_content_index.dat",
            "hnswlib_document_mappings_vector_index.dat"
          ];
          yield chrome.storage.local.remove(storageKeys);
          console.log("VectorDatabase: Chrome storage backup data cleared");
        } catch (error2) {
          console.warn("VectorDatabase: Failed to clear chrome.storage backup:", error2);
        }
        globalVectorDatabase = null;
        currentDimension = null;
        console.log("VectorDatabase: Comprehensive vector data cleanup completed successfully");
      } catch (error2) {
        console.error("VectorDatabase: Comprehensive vector data cleanup failed:", error2);
        throw error2;
      }
    });
  }
  const vectorDatabase = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
    __proto__: null,
    VectorDatabase,
    clearAllVectorData,
    getGlobalVectorDatabase
  }, Symbol.toStringTag, { value: "Module" }));
  const _OffscreenManager = class _OffscreenManager {
    constructor() {
      __publicField2(this, "isCreated", false);
      __publicField2(this, "isCreating", false);
      __publicField2(this, "createPromise", null);
    }
    /**
     * Get singleton instance
     */
    static getInstance() {
      if (!_OffscreenManager.instance) {
        _OffscreenManager.instance = new _OffscreenManager();
      }
      return _OffscreenManager.instance;
    }
    /**
     * Ensure offscreen document exists
     */
    ensureOffscreenDocument() {
      return __async(this, null, function* () {
        if (this.isCreated) {
          return;
        }
        if (this.isCreating && this.createPromise) {
          return this.createPromise;
        }
        this.isCreating = true;
        this.createPromise = this._doCreateOffscreenDocument().finally(() => {
          this.isCreating = false;
        });
        return this.createPromise;
      });
    }
    _doCreateOffscreenDocument() {
      return __async(this, null, function* () {
        try {
          if (!chrome.offscreen) {
            throw new Error("Offscreen API not available. Chrome 109+ required.");
          }
          const existingContexts = yield chrome.runtime.getContexts({
            contextTypes: ["OFFSCREEN_DOCUMENT"]
          });
          if (existingContexts && existingContexts.length > 0) {
            console.log("OffscreenManager: Offscreen document already exists");
            this.isCreated = true;
            return;
          }
          yield chrome.offscreen.createDocument({
            url: "offscreen.html",
            reasons: ["WORKERS"],
            justification: "Need to run semantic similarity engine with workers"
          });
          this.isCreated = true;
          console.log("OffscreenManager: Offscreen document created successfully");
        } catch (error2) {
          console.error("OffscreenManager: Failed to create offscreen document:", error2);
          this.isCreated = false;
          throw error2;
        }
      });
    }
    /**
     * Check if offscreen document is created
     */
    isOffscreenDocumentCreated() {
      return this.isCreated;
    }
    /**
     * Close offscreen document
     */
    closeOffscreenDocument() {
      return __async(this, null, function* () {
        try {
          if (chrome.offscreen && this.isCreated) {
            yield chrome.offscreen.closeDocument();
            this.isCreated = false;
            console.log("OffscreenManager: Offscreen document closed");
          }
        } catch (error2) {
          console.error("OffscreenManager: Failed to close offscreen document:", error2);
        }
      });
    }
    /**
     * Reset state (for testing)
     */
    reset() {
      this.isCreated = false;
      this.isCreating = false;
      this.createPromise = null;
    }
  };
  __publicField2(_OffscreenManager, "instance", null);
  let OffscreenManager = _OffscreenManager;
  OffscreenManager.getInstance();
  function dispatchCallback(progress_callback, data) {
    if (progress_callback) progress_callback(data);
  }
  function reverseDictionary(data) {
    return Object.fromEntries(Object.entries(data).map(([key, value]) => [value, key]));
  }
  const Callable = (
    /** @type {any} */
    class {
      /**
      * Creates a new instance of the Callable class.
      */
      constructor() {
        let closure = function(...args) {
          return closure._call(...args);
        };
        return Object.setPrototypeOf(closure, new.target.prototype);
      }
      /**
       * This method should be implemented in subclasses to provide the
       * functionality of the callable object.
       *
       * @param {any[]} args
       * @throws {Error} If the subclass does not implement the `_call` method.
       */
      _call(...args) {
        throw Error("Must implement _call method in subclass");
      }
    }
  );
  function isTypedArray(val) {
    var _a3, _b2, _c2;
    return ((_c2 = (_b2 = (_a3 = val == null ? void 0 : val.prototype) == null ? void 0 : _a3.__proto__) == null ? void 0 : _b2.constructor) == null ? void 0 : _c2.name) === "TypedArray";
  }
  function isIntegralNumber(x) {
    return Number.isInteger(x) || typeof x === "bigint";
  }
  function exists(x) {
    return x !== void 0 && x !== null;
  }
  function mergeArrays(...arrs) {
    return Array.prototype.concat.apply([], arrs);
  }
  var buffer = {};
  var base64Js = {};
  base64Js.byteLength = byteLength;
  base64Js.toByteArray = toByteArray;
  base64Js.fromByteArray = fromByteArray;
  var lookup = [];
  var revLookup = [];
  var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
  var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  for (var i = 0, len = code.length; i < len; ++i) {
    lookup[i] = code[i];
    revLookup[code.charCodeAt(i)] = i;
  }
  revLookup["-".charCodeAt(0)] = 62;
  revLookup["_".charCodeAt(0)] = 63;
  function getLens(b64) {
    var len2 = b64.length;
    if (len2 % 4 > 0) {
      throw new Error("Invalid string. Length must be a multiple of 4");
    }
    var validLen = b64.indexOf("=");
    if (validLen === -1) validLen = len2;
    var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4;
    return [validLen, placeHoldersLen];
  }
  function byteLength(b64) {
    var lens = getLens(b64);
    var validLen = lens[0];
    var placeHoldersLen = lens[1];
    return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
  }
  function _byteLength(b64, validLen, placeHoldersLen) {
    return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
  }
  function toByteArray(b64) {
    var tmp;
    var lens = getLens(b64);
    var validLen = lens[0];
    var placeHoldersLen = lens[1];
    var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));
    var curByte = 0;
    var len2 = placeHoldersLen > 0 ? validLen - 4 : validLen;
    var i2;
    for (i2 = 0; i2 < len2; i2 += 4) {
      tmp = revLookup[b64.charCodeAt(i2)] << 18 | revLookup[b64.charCodeAt(i2 + 1)] << 12 | revLookup[b64.charCodeAt(i2 + 2)] << 6 | revLookup[b64.charCodeAt(i2 + 3)];
      arr[curByte++] = tmp >> 16 & 255;
      arr[curByte++] = tmp >> 8 & 255;
      arr[curByte++] = tmp & 255;
    }
    if (placeHoldersLen === 2) {
      tmp = revLookup[b64.charCodeAt(i2)] << 2 | revLookup[b64.charCodeAt(i2 + 1)] >> 4;
      arr[curByte++] = tmp & 255;
    }
    if (placeHoldersLen === 1) {
      tmp = revLookup[b64.charCodeAt(i2)] << 10 | revLookup[b64.charCodeAt(i2 + 1)] << 4 | revLookup[b64.charCodeAt(i2 + 2)] >> 2;
      arr[curByte++] = tmp >> 8 & 255;
      arr[curByte++] = tmp & 255;
    }
    return arr;
  }
  function tripletToBase64(num) {
    return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63];
  }
  function encodeChunk(uint8, start, end) {
    var tmp;
    var output = [];
    for (var i2 = start; i2 < end; i2 += 3) {
      tmp = (uint8[i2] << 16 & 16711680) + (uint8[i2 + 1] << 8 & 65280) + (uint8[i2 + 2] & 255);
      output.push(tripletToBase64(tmp));
    }
    return output.join("");
  }
  function fromByteArray(uint8) {
    var tmp;
    var len2 = uint8.length;
    var extraBytes = len2 % 3;
    var parts = [];
    var maxChunkLength = 16383;
    for (var i2 = 0, len22 = len2 - extraBytes; i2 < len22; i2 += maxChunkLength) {
      parts.push(encodeChunk(uint8, i2, i2 + maxChunkLength > len22 ? len22 : i2 + maxChunkLength));
    }
    if (extraBytes === 1) {
      tmp = uint8[len2 - 1];
      parts.push(
        lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "=="
      );
    } else if (extraBytes === 2) {
      tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1];
      parts.push(
        lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "="
      );
    }
    return parts.join("");
  }
  var ieee754 = {};
  ieee754.read = function(buffer2, offset, isLE, mLen, nBytes) {
    var e, m;
    var eLen = nBytes * 8 - mLen - 1;
    var eMax = (1 << eLen) - 1;
    var eBias = eMax >> 1;
    var nBits = -7;
    var i2 = isLE ? nBytes - 1 : 0;
    var d = isLE ? -1 : 1;
    var s = buffer2[offset + i2];
    i2 += d;
    e = s & (1 << -nBits) - 1;
    s >>= -nBits;
    nBits += eLen;
    for (; nBits > 0; e = e * 256 + buffer2[offset + i2], i2 += d, nBits -= 8) {
    }
    m = e & (1 << -nBits) - 1;
    e >>= -nBits;
    nBits += mLen;
    for (; nBits > 0; m = m * 256 + buffer2[offset + i2], i2 += d, nBits -= 8) {
    }
    if (e === 0) {
      e = 1 - eBias;
    } else if (e === eMax) {
      return m ? NaN : (s ? -1 : 1) * Infinity;
    } else {
      m = m + Math.pow(2, mLen);
      e = e - eBias;
    }
    return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
  };
  ieee754.write = function(buffer2, value, offset, isLE, mLen, nBytes) {
    var e, m, c;
    var eLen = nBytes * 8 - mLen - 1;
    var eMax = (1 << eLen) - 1;
    var eBias = eMax >> 1;
    var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
    var i2 = isLE ? 0 : nBytes - 1;
    var d = isLE ? 1 : -1;
    var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
    value = Math.abs(value);
    if (isNaN(value) || value === Infinity) {
      m = isNaN(value) ? 1 : 0;
      e = eMax;
    } else {
      e = Math.floor(Math.log(value) / Math.LN2);
      if (value * (c = Math.pow(2, -e)) < 1) {
        e--;
        c *= 2;
      }
      if (e + eBias >= 1) {
        value += rt / c;
      } else {
        value += rt * Math.pow(2, 1 - eBias);
      }
      if (value * c >= 2) {
        e++;
        c /= 2;
      }
      if (e + eBias >= eMax) {
        m = 0;
        e = eMax;
      } else if (e + eBias >= 1) {
        m = (value * c - 1) * Math.pow(2, mLen);
        e = e + eBias;
      } else {
        m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
        e = 0;
      }
    }
    for (; mLen >= 8; buffer2[offset + i2] = m & 255, i2 += d, m /= 256, mLen -= 8) {
    }
    e = e << mLen | m;
    eLen += mLen;
    for (; eLen > 0; buffer2[offset + i2] = e & 255, i2 += d, e /= 256, eLen -= 8) {
    }
    buffer2[offset + i2 - d] |= s * 128;
  };
  (function(exports$12) {
    const base642 = base64Js;
    const ieee754$1 = ieee754;
    const customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null;
    exports$12.Buffer = Buffer2;
    exports$12.SlowBuffer = SlowBuffer;
    exports$12.INSPECT_MAX_BYTES = 50;
    const K_MAX_LENGTH = 2147483647;
    exports$12.kMaxLength = K_MAX_LENGTH;
    const { Uint8Array: GlobalUint8Array, ArrayBuffer: GlobalArrayBuffer, SharedArrayBuffer: GlobalSharedArrayBuffer } = globalThis;
    Buffer2.TYPED_ARRAY_SUPPORT = typedArraySupport();
    if (!Buffer2.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && typeof console.error === "function") {
      console.error(
        "This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."
      );
    }
    function typedArraySupport() {
      try {
        const arr = new GlobalUint8Array(1);
        const proto = { foo: function() {
          return 42;
        } };
        Object.setPrototypeOf(proto, GlobalUint8Array.prototype);
        Object.setPrototypeOf(arr, proto);
        return arr.foo() === 42;
      } catch (e) {
        return false;
      }
    }
    Object.defineProperty(Buffer2.prototype, "parent", {
      enumerable: true,
      get: function() {
        if (!Buffer2.isBuffer(this)) return void 0;
        return this.buffer;
      }
    });
    Object.defineProperty(Buffer2.prototype, "offset", {
      enumerable: true,
      get: function() {
        if (!Buffer2.isBuffer(this)) return void 0;
        return this.byteOffset;
      }
    });
    function createBuffer(length) {
      if (length > K_MAX_LENGTH) {
        throw new RangeError('The value "' + length + '" is invalid for option "size"');
      }
      const buf = new GlobalUint8Array(length);
      Object.setPrototypeOf(buf, Buffer2.prototype);
      return buf;
    }
    function Buffer2(arg, encodingOrOffset, length) {
      if (typeof arg === "number") {
        if (typeof encodingOrOffset === "string") {
          throw new TypeError(
            'The "string" argument must be of type string. Received type number'
          );
        }
        return allocUnsafe(arg);
      }
      return from(arg, encodingOrOffset, length);
    }
    Buffer2.poolSize = 8192;
    function from(value, encodingOrOffset, length) {
      if (typeof value === "string") {
        return fromString(value, encodingOrOffset);
      }
      if (GlobalArrayBuffer.isView(value)) {
        return fromArrayView(value);
      }
      if (value == null) {
        throw new TypeError(
          "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value
        );
      }
      if (isInstance(value, GlobalArrayBuffer) || value && isInstance(value.buffer, GlobalArrayBuffer)) {
        return fromArrayBuffer(value, encodingOrOffset, length);
      }
      if (typeof GlobalSharedArrayBuffer !== "undefined" && (isInstance(value, GlobalSharedArrayBuffer) || value && isInstance(value.buffer, GlobalSharedArrayBuffer))) {
        return fromArrayBuffer(value, encodingOrOffset, length);
      }
      if (typeof value === "number") {
        throw new TypeError(
          'The "value" argument must not be of type number. Received type number'
        );
      }
      const valueOf = value.valueOf && value.valueOf();
      if (valueOf != null && valueOf !== value) {
        return Buffer2.from(valueOf, encodingOrOffset, length);
      }
      const b = fromObject(value);
      if (b) return b;
      if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === "function") {
        return Buffer2.from(value[Symbol.toPrimitive]("string"), encodingOrOffset, length);
      }
      throw new TypeError(
        "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value
      );
    }
    Buffer2.from = function(value, encodingOrOffset, length) {
      return from(value, encodingOrOffset, length);
    };
    Object.setPrototypeOf(Buffer2.prototype, GlobalUint8Array.prototype);
    Object.setPrototypeOf(Buffer2, GlobalUint8Array);
    function assertSize(size) {
      if (typeof size !== "number") {
        throw new TypeError('"size" argument must be of type number');
      } else if (size < 0) {
        throw new RangeError('The value "' + size + '" is invalid for option "size"');
      }
    }
    function alloc(size, fill, encoding) {
      assertSize(size);
      if (size <= 0) {
        return createBuffer(size);
      }
      if (fill !== void 0) {
        return typeof encoding === "string" ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill);
      }
      return createBuffer(size);
    }
    Buffer2.alloc = function(size, fill, encoding) {
      return alloc(size, fill, encoding);
    };
    function allocUnsafe(size) {
      assertSize(size);
      return createBuffer(size < 0 ? 0 : checked(size) | 0);
    }
    Buffer2.allocUnsafe = function(size) {
      return allocUnsafe(size);
    };
    Buffer2.allocUnsafeSlow = function(size) {
      return allocUnsafe(size);
    };
    function fromString(string2, encoding) {
      if (typeof encoding !== "string" || encoding === "") {
        encoding = "utf8";
      }
      if (!Buffer2.isEncoding(encoding)) {
        throw new TypeError("Unknown encoding: " + encoding);
      }
      const length = byteLength2(string2, encoding) | 0;
      let buf = createBuffer(length);
      const actual = buf.write(string2, encoding);
      if (actual !== length) {
        buf = buf.slice(0, actual);
      }
      return buf;
    }
    function fromArrayLike(array2) {
      const length = array2.length < 0 ? 0 : checked(array2.length) | 0;
      const buf = createBuffer(length);
      for (let i2 = 0; i2 < length; i2 += 1) {
        buf[i2] = array2[i2] & 255;
      }
      return buf;
    }
    function fromArrayView(arrayView) {
      if (isInstance(arrayView, GlobalUint8Array)) {
        const copy = new GlobalUint8Array(arrayView);
        return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength);
      }
      return fromArrayLike(arrayView);
    }
    function fromArrayBuffer(array2, byteOffset, length) {
      if (byteOffset < 0 || array2.byteLength < byteOffset) {
        throw new RangeError('"offset" is outside of buffer bounds');
      }
      if (array2.byteLength < byteOffset + (length || 0)) {
        throw new RangeError('"length" is outside of buffer bounds');
      }
      let buf;
      if (byteOffset === void 0 && length === void 0) {
        buf = new GlobalUint8Array(array2);
      } else if (length === void 0) {
        buf = new GlobalUint8Array(array2, byteOffset);
      } else {
        buf = new GlobalUint8Array(array2, byteOffset, length);
      }
      Object.setPrototypeOf(buf, Buffer2.prototype);
      return buf;
    }
    function fromObject(obj) {
      if (Buffer2.isBuffer(obj)) {
        const len2 = checked(obj.length) | 0;
        const buf = createBuffer(len2);
        if (buf.length === 0) {
          return buf;
        }
        obj.copy(buf, 0, 0, len2);
        return buf;
      }
      if (obj.length !== void 0) {
        if (typeof obj.length !== "number" || numberIsNaN(obj.length)) {
          return createBuffer(0);
        }
        return fromArrayLike(obj);
      }
      if (obj.type === "Buffer" && Array.isArray(obj.data)) {
        return fromArrayLike(obj.data);
      }
    }
    function checked(length) {
      if (length >= K_MAX_LENGTH) {
        throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes");
      }
      return length | 0;
    }
    function SlowBuffer(length) {
      if (+length != length) {
        length = 0;
      }
      return Buffer2.alloc(+length);
    }
    Buffer2.isBuffer = function isBuffer(b) {
      return b != null && b._isBuffer === true && b !== Buffer2.prototype;
    };
    Buffer2.compare = function compare(a, b) {
      if (isInstance(a, GlobalUint8Array)) a = Buffer2.from(a, a.offset, a.byteLength);
      if (isInstance(b, GlobalUint8Array)) b = Buffer2.from(b, b.offset, b.byteLength);
      if (!Buffer2.isBuffer(a) || !Buffer2.isBuffer(b)) {
        throw new TypeError(
          'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
        );
      }
      if (a === b) return 0;
      let x = a.length;
      let y = b.length;
      for (let i2 = 0, len2 = Math.min(x, y); i2 < len2; ++i2) {
        if (a[i2] !== b[i2]) {
          x = a[i2];
          y = b[i2];
          break;
        }
      }
      if (x < y) return -1;
      if (y < x) return 1;
      return 0;
    };
    Buffer2.isEncoding = function isEncoding(encoding) {
      switch (String(encoding).toLowerCase()) {
        case "hex":
        case "utf8":
        case "utf-8":
        case "ascii":
        case "latin1":
        case "binary":
        case "base64":
        case "ucs2":
        case "ucs-2":
        case "utf16le":
        case "utf-16le":
          return true;
        default:
          return false;
      }
    };
    Buffer2.concat = function concat(list, length) {
      if (!Array.isArray(list)) {
        throw new TypeError('"list" argument must be an Array of Buffers');
      }
      if (list.length === 0) {
        return Buffer2.alloc(0);
      }
      let i2;
      if (length === void 0) {
        length = 0;
        for (i2 = 0; i2 < list.length; ++i2) {
          length += list[i2].length;
        }
      }
      const buffer2 = Buffer2.allocUnsafe(length);
      let pos = 0;
      for (i2 = 0; i2 < list.length; ++i2) {
        let buf = list[i2];
        if (isInstance(buf, GlobalUint8Array)) {
          if (pos + buf.length > buffer2.length) {
            if (!Buffer2.isBuffer(buf)) buf = Buffer2.from(buf);
            buf.copy(buffer2, pos);
          } else {
            GlobalUint8Array.prototype.set.call(
              buffer2,
              buf,
              pos
            );
          }
        } else if (!Buffer2.isBuffer(buf)) {
          throw new TypeError('"list" argument must be an Array of Buffers');
        } else {
          buf.copy(buffer2, pos);
        }
        pos += buf.length;
      }
      return buffer2;
    };
    function byteLength2(string2, encoding) {
      if (Buffer2.isBuffer(string2)) {
        return string2.length;
      }
      if (GlobalArrayBuffer.isView(string2) || isInstance(string2, GlobalArrayBuffer)) {
        return string2.byteLength;
      }
      if (typeof string2 !== "string") {
        throw new TypeError(
          'The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof string2
        );
      }
      const len2 = string2.length;
      const mustMatch = arguments.length > 2 && arguments[2] === true;
      if (!mustMatch && len2 === 0) return 0;
      let loweredCase = false;
      for (; ; ) {
        switch (encoding) {
          case "ascii":
          case "latin1":
          case "binary":
            return len2;
          case "utf8":
          case "utf-8":
            return utf8ToBytes(string2).length;
          case "ucs2":
          case "ucs-2":
          case "utf16le":
          case "utf-16le":
            return len2 * 2;
          case "hex":
            return len2 >>> 1;
          case "base64":
            return base64ToBytes(string2).length;
          default:
            if (loweredCase) {
              return mustMatch ? -1 : utf8ToBytes(string2).length;
            }
            encoding = ("" + encoding).toLowerCase();
            loweredCase = true;
        }
      }
    }
    Buffer2.byteLength = byteLength2;
    function slowToString(encoding, start, end) {
      let loweredCase = false;
      if (start === void 0 || start < 0) {
        start = 0;
      }
      if (start > this.length) {
        return "";
      }
      if (end === void 0 || end > this.length) {
        end = this.length;
      }
      if (end <= 0) {
        return "";
      }
      end >>>= 0;
      start >>>= 0;
      if (end <= start) {
        return "";
      }
      if (!encoding) encoding = "utf8";
      while (true) {
        switch (encoding) {
          case "hex":
            return hexSlice(this, start, end);
          case "utf8":
          case "utf-8":
            return utf8Slice(this, start, end);
          case "ascii":
            return asciiSlice(this, start, end);
          case "latin1":
          case "binary":
            return latin1Slice(this, start, end);
          case "base64":
            return base64Slice(this, start, end);
          case "ucs2":
          case "ucs-2":
          case "utf16le":
          case "utf-16le":
            return utf16leSlice(this, start, end);
          default:
            if (loweredCase) throw new TypeError("Unknown encoding: " + encoding);
            encoding = (encoding + "").toLowerCase();
            loweredCase = true;
        }
      }
    }
    Buffer2.prototype._isBuffer = true;
    function swap(b, n, m) {
      const i2 = b[n];
      b[n] = b[m];
      b[m] = i2;
    }
    Buffer2.prototype.swap16 = function swap16() {
      const len2 = this.length;
      if (len2 % 2 !== 0) {
        throw new RangeError("Buffer size must be a multiple of 16-bits");
      }
      for (let i2 = 0; i2 < len2; i2 += 2) {
        swap(this, i2, i2 + 1);
      }
      return this;
    };
    Buffer2.prototype.swap32 = function swap32() {
      const len2 = this.length;
      if (len2 % 4 !== 0) {
        throw new RangeError("Buffer size must be a multiple of 32-bits");
      }
      for (let i2 = 0; i2 < len2; i2 += 4) {
        swap(this, i2, i2 + 3);
        swap(this, i2 + 1, i2 + 2);
      }
      return this;
    };
    Buffer2.prototype.swap64 = function swap64() {
      const len2 = this.length;
      if (len2 % 8 !== 0) {
        throw new RangeError("Buffer size must be a multiple of 64-bits");
      }
      for (let i2 = 0; i2 < len2; i2 += 8) {
        swap(this, i2, i2 + 7);
        swap(this, i2 + 1, i2 + 6);
        swap(this, i2 + 2, i2 + 5);
        swap(this, i2 + 3, i2 + 4);
      }
      return this;
    };
    Buffer2.prototype.toString = function toString() {
      const length = this.length;
      if (length === 0) return "";
      if (arguments.length === 0) return utf8Slice(this, 0, length);
      return slowToString.apply(this, arguments);
    };
    Buffer2.prototype.toLocaleString = Buffer2.prototype.toString;
    Buffer2.prototype.equals = function equals(b) {
      if (!Buffer2.isBuffer(b)) throw new TypeError("Argument must be a Buffer");
      if (this === b) return true;
      return Buffer2.compare(this, b) === 0;
    };
    Buffer2.prototype.inspect = function inspect() {
      let str = "";
      const max2 = exports$12.INSPECT_MAX_BYTES;
      str = this.toString("hex", 0, max2).replace(/(.{2})/g, "$1 ").trim();
      if (this.length > max2) str += " ... ";
      return "<Buffer " + str + ">";
    };
    if (customInspectSymbol) {
      Buffer2.prototype[customInspectSymbol] = Buffer2.prototype.inspect;
    }
    Buffer2.prototype.compare = function compare(target, start, end, thisStart, thisEnd) {
      if (isInstance(target, GlobalUint8Array)) {
        target = Buffer2.from(target, target.offset, target.byteLength);
      }
      if (!Buffer2.isBuffer(target)) {
        throw new TypeError(
          'The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof target
        );
      }
      if (start === void 0) {
        start = 0;
      }
      if (end === void 0) {
        end = target ? target.length : 0;
      }
      if (thisStart === void 0) {
        thisStart = 0;
      }
      if (thisEnd === void 0) {
        thisEnd = this.length;
      }
      if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
        throw new RangeError("out of range index");
      }
      if (thisStart >= thisEnd && start >= end) {
        return 0;
      }
      if (thisStart >= thisEnd) {
        return -1;
      }
      if (start >= end) {
        return 1;
      }
      start >>>= 0;
      end >>>= 0;
      thisStart >>>= 0;
      thisEnd >>>= 0;
      if (this === target) return 0;
      let x = thisEnd - thisStart;
      let y = end - start;
      const len2 = Math.min(x, y);
      const thisCopy = this.slice(thisStart, thisEnd);
      const targetCopy = target.slice(start, end);
      for (let i2 = 0; i2 < len2; ++i2) {
        if (thisCopy[i2] !== targetCopy[i2]) {
          x = thisCopy[i2];
          y = targetCopy[i2];
          break;
        }
      }
      if (x < y) return -1;
      if (y < x) return 1;
      return 0;
    };
    function bidirectionalIndexOf(buffer2, val, byteOffset, encoding, dir) {
      if (buffer2.length === 0) return -1;
      if (typeof byteOffset === "string") {
        encoding = byteOffset;
        byteOffset = 0;
      } else if (byteOffset > 2147483647) {
        byteOffset = 2147483647;
      } else if (byteOffset < -2147483648) {
        byteOffset = -2147483648;
      }
      byteOffset = +byteOffset;
      if (numberIsNaN(byteOffset)) {
        byteOffset = dir ? 0 : buffer2.length - 1;
      }
      if (byteOffset < 0) byteOffset = buffer2.length + byteOffset;
      if (byteOffset >= buffer2.length) {
        if (dir) return -1;
        else byteOffset = buffer2.length - 1;
      } else if (byteOffset < 0) {
        if (dir) byteOffset = 0;
        else return -1;
      }
      if (typeof val === "string") {
        val = Buffer2.from(val, encoding);
      }
      if (Buffer2.isBuffer(val)) {
        if (val.length === 0) {
          return -1;
        }
        return arrayIndexOf(buffer2, val, byteOffset, encoding, dir);
      } else if (typeof val === "number") {
        val = val & 255;
        if (typeof GlobalUint8Array.prototype.indexOf === "function") {
          if (dir) {
            return GlobalUint8Array.prototype.indexOf.call(buffer2, val, byteOffset);
          } else {
            return GlobalUint8Array.prototype.lastIndexOf.call(buffer2, val, byteOffset);
          }
        }
        return arrayIndexOf(buffer2, [val], byteOffset, encoding, dir);
      }
      throw new TypeError("val must be string, number or Buffer");
    }
    function arrayIndexOf(arr, val, byteOffset, encoding, dir) {
      let indexSize = 1;
      let arrLength = arr.length;
      let valLength = val.length;
      if (encoding !== void 0) {
        encoding = String(encoding).toLowerCase();
        if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") {
          if (arr.length < 2 || val.length < 2) {
            return -1;
          }
          indexSize = 2;
          arrLength /= 2;
          valLength /= 2;
          byteOffset /= 2;
        }
      }
      function read(buf, i3) {
        if (indexSize === 1) {
          return buf[i3];
        } else {
          return buf.readUInt16BE(i3 * indexSize);
        }
      }
      let i2;
      if (dir) {
        let foundIndex = -1;
        for (i2 = byteOffset; i2 < arrLength; i2++) {
          if (read(arr, i2) === read(val, foundIndex === -1 ? 0 : i2 - foundIndex)) {
            if (foundIndex === -1) foundIndex = i2;
            if (i2 - foundIndex + 1 === valLength) return foundIndex * indexSize;
          } else {
            if (foundIndex !== -1) i2 -= i2 - foundIndex;
            foundIndex = -1;
          }
        }
      } else {
        if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
        for (i2 = byteOffset; i2 >= 0; i2--) {
          let found = true;
          for (let j = 0; j < valLength; j++) {
            if (read(arr, i2 + j) !== read(val, j)) {
              found = false;
              break;
            }
          }
          if (found) return i2;
        }
      }
      return -1;
    }
    Buffer2.prototype.includes = function includes(val, byteOffset, encoding) {
      return this.indexOf(val, byteOffset, encoding) !== -1;
    };
    Buffer2.prototype.indexOf = function indexOf(val, byteOffset, encoding) {
      return bidirectionalIndexOf(this, val, byteOffset, encoding, true);
    };
    Buffer2.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
      return bidirectionalIndexOf(this, val, byteOffset, encoding, false);
    };
    function hexWrite(buf, string2, offset, length) {
      offset = Number(offset) || 0;
      const remaining = buf.length - offset;
      if (!length) {
        length = remaining;
      } else {
        length = Number(length);
        if (length > remaining) {
          length = remaining;
        }
      }
      const strLen = string2.length;
      if (length > strLen / 2) {
        length = strLen / 2;
      }
      let i2;
      for (i2 = 0; i2 < length; ++i2) {
        const parsed = parseInt(string2.substr(i2 * 2, 2), 16);
        if (numberIsNaN(parsed)) return i2;
        buf[offset + i2] = parsed;
      }
      return i2;
    }
    function utf8Write(buf, string2, offset, length) {
      return blitBuffer(utf8ToBytes(string2, buf.length - offset), buf, offset, length);
    }
    function asciiWrite(buf, string2, offset, length) {
      return blitBuffer(asciiToBytes(string2), buf, offset, length);
    }
    function base64Write(buf, string2, offset, length) {
      return blitBuffer(base64ToBytes(string2), buf, offset, length);
    }
    function ucs2Write(buf, string2, offset, length) {
      return blitBuffer(utf16leToBytes(string2, buf.length - offset), buf, offset, length);
    }
    Buffer2.prototype.write = function write(string2, offset, length, encoding) {
      if (offset === void 0) {
        encoding = "utf8";
        length = this.length;
        offset = 0;
      } else if (length === void 0 && typeof offset === "string") {
        encoding = offset;
        length = this.length;
        offset = 0;
      } else if (isFinite(offset)) {
        offset = offset >>> 0;
        if (isFinite(length)) {
          length = length >>> 0;
          if (encoding === void 0) encoding = "utf8";
        } else {
          encoding = length;
          length = void 0;
        }
      } else {
        throw new Error(
          "Buffer.write(string, encoding, offset[, length]) is no longer supported"
        );
      }
      const remaining = this.length - offset;
      if (length === void 0 || length > remaining) length = remaining;
      if (string2.length > 0 && (length < 0 || offset < 0) || offset > this.length) {
        throw new RangeError("Attempt to write outside buffer bounds");
      }
      if (!encoding) encoding = "utf8";
      let loweredCase = false;
      for (; ; ) {
        switch (encoding) {
          case "hex":
            return hexWrite(this, string2, offset, length);
          case "utf8":
          case "utf-8":
            return utf8Write(this, string2, offset, length);
          case "ascii":
          case "latin1":
          case "binary":
            return asciiWrite(this, string2, offset, length);
          case "base64":
            return base64Write(this, string2, offset, length);
          case "ucs2":
          case "ucs-2":
          case "utf16le":
          case "utf-16le":
            return ucs2Write(this, string2, offset, length);
          default:
            if (loweredCase) throw new TypeError("Unknown encoding: " + encoding);
            encoding = ("" + encoding).toLowerCase();
            loweredCase = true;
        }
      }
    };
    Buffer2.prototype.toJSON = function toJSON() {
      return {
        type: "Buffer",
        data: Array.prototype.slice.call(this._arr || this, 0)
      };
    };
    function base64Slice(buf, start, end) {
      if (start === 0 && end === buf.length) {
        return base642.fromByteArray(buf);
      } else {
        return base642.fromByteArray(buf.slice(start, end));
      }
    }
    function utf8Slice(buf, start, end) {
      end = Math.min(buf.length, end);
      const res = [];
      let i2 = start;
      while (i2 < end) {
        const firstByte = buf[i2];
        let codePoint = null;
        let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1;
        if (i2 + bytesPerSequence <= end) {
          let secondByte, thirdByte, fourthByte, tempCodePoint;
          switch (bytesPerSequence) {
            case 1:
              if (firstByte < 128) {
                codePoint = firstByte;
              }
              break;
            case 2:
              secondByte = buf[i2 + 1];
              if ((secondByte & 192) === 128) {
                tempCodePoint = (firstByte & 31) << 6 | secondByte & 63;
                if (tempCodePoint > 127) {
                  codePoint = tempCodePoint;
                }
              }
              break;
            case 3:
              secondByte = buf[i2 + 1];
              thirdByte = buf[i2 + 2];
              if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) {
                tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63;
                if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) {
                  codePoint = tempCodePoint;
                }
              }
              break;
            case 4:
              secondByte = buf[i2 + 1];
              thirdByte = buf[i2 + 2];
              fourthByte = buf[i2 + 3];
              if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) {
                tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63;
                if (tempCodePoint > 65535 && tempCodePoint < 1114112) {
                  codePoint = tempCodePoint;
                }
              }
          }
        }
        if (codePoint === null) {
          codePoint = 65533;
          bytesPerSequence = 1;
        } else if (codePoint > 65535) {
          codePoint -= 65536;
          res.push(codePoint >>> 10 & 1023 | 55296);
          codePoint = 56320 | codePoint & 1023;
        }
        res.push(codePoint);
        i2 += bytesPerSequence;
      }
      return decodeCodePointsArray(res);
    }
    const MAX_ARGUMENTS_LENGTH = 4096;
    function decodeCodePointsArray(codePoints) {
      const len2 = codePoints.length;
      if (len2 <= MAX_ARGUMENTS_LENGTH) {
        return String.fromCharCode.apply(String, codePoints);
      }
      let res = "";
      let i2 = 0;
      while (i2 < len2) {
        res += String.fromCharCode.apply(
          String,
          codePoints.slice(i2, i2 += MAX_ARGUMENTS_LENGTH)
        );
      }
      return res;
    }
    function asciiSlice(buf, start, end) {
      let ret = "";
      end = Math.min(buf.length, end);
      for (let i2 = start; i2 < end; ++i2) {
        ret += String.fromCharCode(buf[i2] & 127);
      }
      return ret;
    }
    function latin1Slice(buf, start, end) {
      let ret = "";
      end = Math.min(buf.length, end);
      for (let i2 = start; i2 < end; ++i2) {
        ret += String.fromCharCode(buf[i2]);
      }
      return ret;
    }
    function hexSlice(buf, start, end) {
      const len2 = buf.length;
      if (!start || start < 0) start = 0;
      if (!end || end < 0 || end > len2) end = len2;
      let out = "";
      for (let i2 = start; i2 < end; ++i2) {
        out += hexSliceLookupTable[buf[i2]];
      }
      return out;
    }
    function utf16leSlice(buf, start, end) {
      const bytes = buf.slice(start, end);
      let res = "";
      for (let i2 = 0; i2 < bytes.length - 1; i2 += 2) {
        res += String.fromCharCode(bytes[i2] + bytes[i2 + 1] * 256);
      }
      return res;
    }
    Buffer2.prototype.slice = function slice(start, end) {
      const len2 = this.length;
      start = ~~start;
      end = end === void 0 ? len2 : ~~end;
      if (start < 0) {
        start += len2;
        if (start < 0) start = 0;
      } else if (start > len2) {
        start = len2;
      }
      if (end < 0) {
        end += len2;
        if (end < 0) end = 0;
      } else if (end > len2) {
        end = len2;
      }
      if (end < start) end = start;
      const newBuf = this.subarray(start, end);
      Object.setPrototypeOf(newBuf, Buffer2.prototype);
      return newBuf;
    };
    function checkOffset(offset, ext, length) {
      if (offset % 1 !== 0 || offset < 0) throw new RangeError("offset is not uint");
      if (offset + ext > length) throw new RangeError("Trying to access beyond buffer length");
    }
    Buffer2.prototype.readUintLE = Buffer2.prototype.readUIntLE = function readUIntLE(offset, byteLength3, noAssert) {
      offset = offset >>> 0;
      byteLength3 = byteLength3 >>> 0;
      if (!noAssert) checkOffset(offset, byteLength3, this.length);
      let val = this[offset];
      let mul = 1;
      let i2 = 0;
      while (++i2 < byteLength3 && (mul *= 256)) {
        val += this[offset + i2] * mul;
      }
      return val;
    };
    Buffer2.prototype.readUintBE = Buffer2.prototype.readUIntBE = function readUIntBE(offset, byteLength3, noAssert) {
      offset = offset >>> 0;
      byteLength3 = byteLength3 >>> 0;
      if (!noAssert) {
        checkOffset(offset, byteLength3, this.length);
      }
      let val = this[offset + --byteLength3];
      let mul = 1;
      while (byteLength3 > 0 && (mul *= 256)) {
        val += this[offset + --byteLength3] * mul;
      }
      return val;
    };
    Buffer2.prototype.readUint8 = Buffer2.prototype.readUInt8 = function readUInt8(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert) checkOffset(offset, 1, this.length);
      return this[offset];
    };
    Buffer2.prototype.readUint16LE = Buffer2.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert) checkOffset(offset, 2, this.length);
      return this[offset] | this[offset + 1] << 8;
    };
    Buffer2.prototype.readUint16BE = Buffer2.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert) checkOffset(offset, 2, this.length);
      return this[offset] << 8 | this[offset + 1];
    };
    Buffer2.prototype.readUint32LE = Buffer2.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert) checkOffset(offset, 4, this.length);
      return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216;
    };
    Buffer2.prototype.readUint32BE = Buffer2.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert) checkOffset(offset, 4, this.length);
      return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]);
    };
    Buffer2.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE(offset) {
      offset = offset >>> 0;
      validateNumber(offset, "offset");
      const first = this[offset];
      const last = this[offset + 7];
      if (first === void 0 || last === void 0) {
        boundsError(offset, this.length - 8);
      }
      const lo = first + this[++offset] * __pow(2, 8) + this[++offset] * __pow(2, 16) + this[++offset] * __pow(2, 24);
      const hi = this[++offset] + this[++offset] * __pow(2, 8) + this[++offset] * __pow(2, 16) + last * __pow(2, 24);
      return BigInt(lo) + (BigInt(hi) << BigInt(32));
    });
    Buffer2.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE(offset) {
      offset = offset >>> 0;
      validateNumber(offset, "offset");
      const first = this[offset];
      const last = this[offset + 7];
      if (first === void 0 || last === void 0) {
        boundsError(offset, this.length - 8);
      }
      const hi = first * __pow(2, 24) + this[++offset] * __pow(2, 16) + this[++offset] * __pow(2, 8) + this[++offset];
      const lo = this[++offset] * __pow(2, 24) + this[++offset] * __pow(2, 16) + this[++offset] * __pow(2, 8) + last;
      return (BigInt(hi) << BigInt(32)) + BigInt(lo);
    });
    Buffer2.prototype.readIntLE = function readIntLE(offset, byteLength3, noAssert) {
      offset = offset >>> 0;
      byteLength3 = byteLength3 >>> 0;
      if (!noAssert) checkOffset(offset, byteLength3, this.length);
      let val = this[offset];
      let mul = 1;
      let i2 = 0;
      while (++i2 < byteLength3 && (mul *= 256)) {
        val += this[offset + i2] * mul;
      }
      mul *= 128;
      if (val >= mul) val -= Math.pow(2, 8 * byteLength3);
      return val;
    };
    Buffer2.prototype.readIntBE = function readIntBE(offset, byteLength3, noAssert) {
      offset = offset >>> 0;
      byteLength3 = byteLength3 >>> 0;
      if (!noAssert) checkOffset(offset, byteLength3, this.length);
      let i2 = byteLength3;
      let mul = 1;
      let val = this[offset + --i2];
      while (i2 > 0 && (mul *= 256)) {
        val += this[offset + --i2] * mul;
      }
      mul *= 128;
      if (val >= mul) val -= Math.pow(2, 8 * byteLength3);
      return val;
    };
    Buffer2.prototype.readInt8 = function readInt8(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert) checkOffset(offset, 1, this.length);
      if (!(this[offset] & 128)) return this[offset];
      return (255 - this[offset] + 1) * -1;
    };
    Buffer2.prototype.readInt16LE = function readInt16LE(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert) checkOffset(offset, 2, this.length);
      const val = this[offset] | this[offset + 1] << 8;
      return val & 32768 ? val | 4294901760 : val;
    };
    Buffer2.prototype.readInt16BE = function readInt16BE(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert) checkOffset(offset, 2, this.length);
      const val = this[offset + 1] | this[offset] << 8;
      return val & 32768 ? val | 4294901760 : val;
    };
    Buffer2.prototype.readInt32LE = function readInt32LE(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert) checkOffset(offset, 4, this.length);
      return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24;
    };
    Buffer2.prototype.readInt32BE = function readInt32BE(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert) checkOffset(offset, 4, this.length);
      return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3];
    };
    Buffer2.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE(offset) {
      offset = offset >>> 0;
      validateNumber(offset, "offset");
      const first = this[offset];
      const last = this[offset + 7];
      if (first === void 0 || last === void 0) {
        boundsError(offset, this.length - 8);
      }
      const val = this[offset + 4] + this[offset + 5] * __pow(2, 8) + this[offset + 6] * __pow(2, 16) + (last << 24);
      return (BigInt(val) << BigInt(32)) + BigInt(first + this[++offset] * __pow(2, 8) + this[++offset] * __pow(2, 16) + this[++offset] * __pow(2, 24));
    });
    Buffer2.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE(offset) {
      offset = offset >>> 0;
      validateNumber(offset, "offset");
      const first = this[offset];
      const last = this[offset + 7];
      if (first === void 0 || last === void 0) {
        boundsError(offset, this.length - 8);
      }
      const val = (first << 24) + // Overflow
      this[++offset] * __pow(2, 16) + this[++offset] * __pow(2, 8) + this[++offset];
      return (BigInt(val) << BigInt(32)) + BigInt(this[++offset] * __pow(2, 24) + this[++offset] * __pow(2, 16) + this[++offset] * __pow(2, 8) + last);
    });
    Buffer2.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert) checkOffset(offset, 4, this.length);
      return ieee754$1.read(this, offset, true, 23, 4);
    };
    Buffer2.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert) checkOffset(offset, 4, this.length);
      return ieee754$1.read(this, offset, false, 23, 4);
    };
    Buffer2.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert) checkOffset(offset, 8, this.length);
      return ieee754$1.read(this, offset, true, 52, 8);
    };
    Buffer2.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
      offset = offset >>> 0;
      if (!noAssert) checkOffset(offset, 8, this.length);
      return ieee754$1.read(this, offset, false, 52, 8);
    };
    function checkInt(buf, value, offset, ext, max2, min) {
      if (!Buffer2.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance');
      if (value > max2 || value < min) throw new RangeError('"value" argument is out of bounds');
      if (offset + ext > buf.length) throw new RangeError("Index out of range");
    }
    Buffer2.prototype.writeUintLE = Buffer2.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength3, noAssert) {
      value = +value;
      offset = offset >>> 0;
      byteLength3 = byteLength3 >>> 0;
      if (!noAssert) {
        const maxBytes = Math.pow(2, 8 * byteLength3) - 1;
        checkInt(this, value, offset, byteLength3, maxBytes, 0);
      }
      let mul = 1;
      let i2 = 0;
      this[offset] = value & 255;
      while (++i2 < byteLength3 && (mul *= 256)) {
        this[offset + i2] = value / mul & 255;
      }
      return offset + byteLength3;
    };
    Buffer2.prototype.writeUintBE = Buffer2.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength3, noAssert) {
      value = +value;
      offset = offset >>> 0;
      byteLength3 = byteLength3 >>> 0;
      if (!noAssert) {
        const maxBytes = Math.pow(2, 8 * byteLength3) - 1;
        checkInt(this, value, offset, byteLength3, maxBytes, 0);
      }
      let i2 = byteLength3 - 1;
      let mul = 1;
      this[offset + i2] = value & 255;
      while (--i2 >= 0 && (mul *= 256)) {
        this[offset + i2] = value / mul & 255;
      }
      return offset + byteLength3;
    };
    Buffer2.prototype.writeUint8 = Buffer2.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert) checkInt(this, value, offset, 1, 255, 0);
      this[offset] = value & 255;
      return offset + 1;
    };
    Buffer2.prototype.writeUint16LE = Buffer2.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert) checkInt(this, value, offset, 2, 65535, 0);
      this[offset] = value & 255;
      this[offset + 1] = value >>> 8;
      return offset + 2;
    };
    Buffer2.prototype.writeUint16BE = Buffer2.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert) checkInt(this, value, offset, 2, 65535, 0);
      this[offset] = value >>> 8;
      this[offset + 1] = value & 255;
      return offset + 2;
    };
    Buffer2.prototype.writeUint32LE = Buffer2.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert) checkInt(this, value, offset, 4, 4294967295, 0);
      this[offset + 3] = value >>> 24;
      this[offset + 2] = value >>> 16;
      this[offset + 1] = value >>> 8;
      this[offset] = value & 255;
      return offset + 4;
    };
    Buffer2.prototype.writeUint32BE = Buffer2.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert) checkInt(this, value, offset, 4, 4294967295, 0);
      this[offset] = value >>> 24;
      this[offset + 1] = value >>> 16;
      this[offset + 2] = value >>> 8;
      this[offset + 3] = value & 255;
      return offset + 4;
    };
    function wrtBigUInt64LE(buf, value, offset, min, max2) {
      checkIntBI(value, min, max2, buf, offset, 7);
      let lo = Number(value & BigInt(4294967295));
      buf[offset++] = lo;
      lo = lo >> 8;
      buf[offset++] = lo;
      lo = lo >> 8;
      buf[offset++] = lo;
      lo = lo >> 8;
      buf[offset++] = lo;
      let hi = Number(value >> BigInt(32) & BigInt(4294967295));
      buf[offset++] = hi;
      hi = hi >> 8;
      buf[offset++] = hi;
      hi = hi >> 8;
      buf[offset++] = hi;
      hi = hi >> 8;
      buf[offset++] = hi;
      return offset;
    }
    function wrtBigUInt64BE(buf, value, offset, min, max2) {
      checkIntBI(value, min, max2, buf, offset, 7);
      let lo = Number(value & BigInt(4294967295));
      buf[offset + 7] = lo;
      lo = lo >> 8;
      buf[offset + 6] = lo;
      lo = lo >> 8;
      buf[offset + 5] = lo;
      lo = lo >> 8;
      buf[offset + 4] = lo;
      let hi = Number(value >> BigInt(32) & BigInt(4294967295));
      buf[offset + 3] = hi;
      hi = hi >> 8;
      buf[offset + 2] = hi;
      hi = hi >> 8;
      buf[offset + 1] = hi;
      hi = hi >> 8;
      buf[offset] = hi;
      return offset + 8;
    }
    Buffer2.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE(value, offset = 0) {
      return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff"));
    });
    Buffer2.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE(value, offset = 0) {
      return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff"));
    });
    Buffer2.prototype.writeIntLE = function writeIntLE(value, offset, byteLength3, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert) {
        const limit2 = Math.pow(2, 8 * byteLength3 - 1);
        checkInt(this, value, offset, byteLength3, limit2 - 1, -limit2);
      }
      let i2 = 0;
      let mul = 1;
      let sub = 0;
      this[offset] = value & 255;
      while (++i2 < byteLength3 && (mul *= 256)) {
        if (value < 0 && sub === 0 && this[offset + i2 - 1] !== 0) {
          sub = 1;
        }
        this[offset + i2] = (value / mul >> 0) - sub & 255;
      }
      return offset + byteLength3;
    };
    Buffer2.prototype.writeIntBE = function writeIntBE(value, offset, byteLength3, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert) {
        const limit2 = Math.pow(2, 8 * byteLength3 - 1);
        checkInt(this, value, offset, byteLength3, limit2 - 1, -limit2);
      }
      let i2 = byteLength3 - 1;
      let mul = 1;
      let sub = 0;
      this[offset + i2] = value & 255;
      while (--i2 >= 0 && (mul *= 256)) {
        if (value < 0 && sub === 0 && this[offset + i2 + 1] !== 0) {
          sub = 1;
        }
        this[offset + i2] = (value / mul >> 0) - sub & 255;
      }
      return offset + byteLength3;
    };
    Buffer2.prototype.writeInt8 = function writeInt8(value, offset, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert) checkInt(this, value, offset, 1, 127, -128);
      if (value < 0) value = 255 + value + 1;
      this[offset] = value & 255;
      return offset + 1;
    };
    Buffer2.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert) checkInt(this, value, offset, 2, 32767, -32768);
      this[offset] = value & 255;
      this[offset + 1] = value >>> 8;
      return offset + 2;
    };
    Buffer2.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert) checkInt(this, value, offset, 2, 32767, -32768);
      this[offset] = value >>> 8;
      this[offset + 1] = value & 255;
      return offset + 2;
    };
    Buffer2.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert) checkInt(this, value, offset, 4, 2147483647, -2147483648);
      this[offset] = value & 255;
      this[offset + 1] = value >>> 8;
      this[offset + 2] = value >>> 16;
      this[offset + 3] = value >>> 24;
      return offset + 4;
    };
    Buffer2.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert) checkInt(this, value, offset, 4, 2147483647, -2147483648);
      if (value < 0) value = 4294967295 + value + 1;
      this[offset] = value >>> 24;
      this[offset + 1] = value >>> 16;
      this[offset + 2] = value >>> 8;
      this[offset + 3] = value & 255;
      return offset + 4;
    };
    Buffer2.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE(value, offset = 0) {
      return wrtBigUInt64LE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
    });
    Buffer2.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE(value, offset = 0) {
      return wrtBigUInt64BE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
    });
    function checkIEEE754(buf, value, offset, ext, max2, min) {
      if (offset + ext > buf.length) throw new RangeError("Index out of range");
      if (offset < 0) throw new RangeError("Index out of range");
    }
    function writeFloat(buf, value, offset, littleEndian, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert) {
        checkIEEE754(buf, value, offset, 4);
      }
      ieee754$1.write(buf, value, offset, littleEndian, 23, 4);
      return offset + 4;
    }
    Buffer2.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) {
      return writeFloat(this, value, offset, true, noAssert);
    };
    Buffer2.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) {
      return writeFloat(this, value, offset, false, noAssert);
    };
    function writeDouble(buf, value, offset, littleEndian, noAssert) {
      value = +value;
      offset = offset >>> 0;
      if (!noAssert) {
        checkIEEE754(buf, value, offset, 8);
      }
      ieee754$1.write(buf, value, offset, littleEndian, 52, 8);
      return offset + 8;
    }
    Buffer2.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) {
      return writeDouble(this, value, offset, true, noAssert);
    };
    Buffer2.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) {
      return writeDouble(this, value, offset, false, noAssert);
    };
    Buffer2.prototype.copy = function copy(target, targetStart, start, end) {
      if (!Buffer2.isBuffer(target)) throw new TypeError("argument should be a Buffer");
      if (!start) start = 0;
      if (!end && end !== 0) end = this.length;
      if (targetStart >= target.length) targetStart = target.length;
      if (!targetStart) targetStart = 0;
      if (end > 0 && end < start) end = start;
      if (end === start) return 0;
      if (target.length === 0 || this.length === 0) return 0;
      if (targetStart < 0) {
        throw new RangeError("targetStart out of bounds");
      }
      if (start < 0 || start >= this.length) throw new RangeError("Index out of range");
      if (end < 0) throw new RangeError("sourceEnd out of bounds");
      if (end > this.length) end = this.length;
      if (target.length - targetStart < end - start) {
        end = target.length - targetStart + start;
      }
      const len2 = end - start;
      if (this === target && typeof GlobalUint8Array.prototype.copyWithin === "function") {
        this.copyWithin(targetStart, start, end);
      } else {
        GlobalUint8Array.prototype.set.call(
          target,
          this.subarray(start, end),
          targetStart
        );
      }
      return len2;
    };
    Buffer2.prototype.fill = function fill(val, start, end, encoding) {
      if (typeof val === "string") {
        if (typeof start === "string") {
          encoding = start;
          start = 0;
          end = this.length;
        } else if (typeof end === "string") {
          encoding = end;
          end = this.length;
        }
        if (encoding !== void 0 && typeof encoding !== "string") {
          throw new TypeError("encoding must be a string");
        }
        if (typeof encoding === "string" && !Buffer2.isEncoding(encoding)) {
          throw new TypeError("Unknown encoding: " + encoding);
        }
        if (val.length === 1) {
          const code2 = val.charCodeAt(0);
          if (encoding === "utf8" && code2 < 128 || encoding === "latin1") {
            val = code2;
          }
        }
      } else if (typeof val === "number") {
        val = val & 255;
      } else if (typeof val === "boolean") {
        val = Number(val);
      }
      if (start < 0 || this.length < start || this.length < end) {
        throw new RangeError("Out of range index");
      }
      if (end <= start) {
        return this;
      }
      start = start >>> 0;
      end = end === void 0 ? this.length : end >>> 0;
      if (!val) val = 0;
      let i2;
      if (typeof val === "number") {
        for (i2 = start; i2 < end; ++i2) {
          this[i2] = val;
        }
      } else {
        const bytes = Buffer2.isBuffer(val) ? val : Buffer2.from(val, encoding);
        const len2 = bytes.length;
        if (len2 === 0) {
          throw new TypeError('The value "' + val + '" is invalid for argument "value"');
        }
        for (i2 = 0; i2 < end - start; ++i2) {
          this[i2 + start] = bytes[i2 % len2];
        }
      }
      return this;
    };
    const errors2 = {};
    function E(sym, getMessage, Base) {
      errors2[sym] = class NodeError extends Base {
        constructor() {
          super();
          Object.defineProperty(this, "message", {
            value: getMessage.apply(this, arguments),
            writable: true,
            configurable: true
          });
          this.name = `${this.name} [${sym}]`;
          this.stack;
          delete this.name;
        }
        get code() {
          return sym;
        }
        set code(value) {
          Object.defineProperty(this, "code", {
            configurable: true,
            enumerable: true,
            value,
            writable: true
          });
        }
        toString() {
          return `${this.name} [${sym}]: ${this.message}`;
        }
      };
    }
    E(
      "ERR_BUFFER_OUT_OF_BOUNDS",
      function(name2) {
        if (name2) {
          return `${name2} is outside of buffer bounds`;
        }
        return "Attempt to access memory outside buffer bounds";
      },
      RangeError
    );
    E(
      "ERR_INVALID_ARG_TYPE",
      function(name2, actual) {
        return `The "${name2}" argument must be of type number. Received type ${typeof actual}`;
      },
      TypeError
    );
    E(
      "ERR_OUT_OF_RANGE",
      function(str, range, input) {
        let msg = `The value of "${str}" is out of range.`;
        let received = input;
        if (Number.isInteger(input) && Math.abs(input) > __pow(2, 32)) {
          received = addNumericalSeparator(String(input));
        } else if (typeof input === "bigint") {
          received = String(input);
          if (input > __pow(BigInt(2), BigInt(32)) || input < -__pow(BigInt(2), BigInt(32))) {
            received = addNumericalSeparator(received);
          }
          received += "n";
        }
        msg += ` It must be ${range}. Received ${received}`;
        return msg;
      },
      RangeError
    );
    function addNumericalSeparator(val) {
      let res = "";
      let i2 = val.length;
      const start = val[0] === "-" ? 1 : 0;
      for (; i2 >= start + 4; i2 -= 3) {
        res = `_${val.slice(i2 - 3, i2)}${res}`;
      }
      return `${val.slice(0, i2)}${res}`;
    }
    function checkBounds(buf, offset, byteLength3) {
      validateNumber(offset, "offset");
      if (buf[offset] === void 0 || buf[offset + byteLength3] === void 0) {
        boundsError(offset, buf.length - (byteLength3 + 1));
      }
    }
    function checkIntBI(value, min, max2, buf, offset, byteLength3) {
      if (value > max2 || value < min) {
        const n = typeof min === "bigint" ? "n" : "";
        let range;
        {
          if (min === 0 || min === BigInt(0)) {
            range = `>= 0${n} and < 2${n} ** ${(byteLength3 + 1) * 8}${n}`;
          } else {
            range = `>= -(2${n} ** ${(byteLength3 + 1) * 8 - 1}${n}) and < 2 ** ${(byteLength3 + 1) * 8 - 1}${n}`;
          }
        }
        throw new errors2.ERR_OUT_OF_RANGE("value", range, value);
      }
      checkBounds(buf, offset, byteLength3);
    }
    function validateNumber(value, name2) {
      if (typeof value !== "number") {
        throw new errors2.ERR_INVALID_ARG_TYPE(name2, "number", value);
      }
    }
    function boundsError(value, length, type2) {
      if (Math.floor(value) !== value) {
        validateNumber(value, type2);
        throw new errors2.ERR_OUT_OF_RANGE("offset", "an integer", value);
      }
      if (length < 0) {
        throw new errors2.ERR_BUFFER_OUT_OF_BOUNDS();
      }
      throw new errors2.ERR_OUT_OF_RANGE(
        "offset",
        `>= ${0} and <= ${length}`,
        value
      );
    }
    const INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
    function base64clean(str) {
      str = str.split("=")[0];
      str = str.trim().replace(INVALID_BASE64_RE, "");
      if (str.length < 2) return "";
      while (str.length % 4 !== 0) {
        str = str + "=";
      }
      return str;
    }
    function utf8ToBytes(string2, units) {
      units = units || Infinity;
      let codePoint;
      const length = string2.length;
      let leadSurrogate = null;
      const bytes = [];
      for (let i2 = 0; i2 < length; ++i2) {
        codePoint = string2.charCodeAt(i2);
        if (codePoint > 55295 && codePoint < 57344) {
          if (!leadSurrogate) {
            if (codePoint > 56319) {
              if ((units -= 3) > -1) bytes.push(239, 191, 189);
              continue;
            } else if (i2 + 1 === length) {
              if ((units -= 3) > -1) bytes.push(239, 191, 189);
              continue;
            }
            leadSurrogate = codePoint;
            continue;
          }
          if (codePoint < 56320) {
            if ((units -= 3) > -1) bytes.push(239, 191, 189);
            leadSurrogate = codePoint;
            continue;
          }
          codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536;
        } else if (leadSurrogate) {
          if ((units -= 3) > -1) bytes.push(239, 191, 189);
        }
        leadSurrogate = null;
        if (codePoint < 128) {
          if ((units -= 1) < 0) break;
          bytes.push(codePoint);
        } else if (codePoint < 2048) {
          if ((units -= 2) < 0) break;
          bytes.push(
            codePoint >> 6 | 192,
            codePoint & 63 | 128
          );
        } else if (codePoint < 65536) {
          if ((units -= 3) < 0) break;
          bytes.push(
            codePoint >> 12 | 224,
            codePoint >> 6 & 63 | 128,
            codePoint & 63 | 128
          );
        } else if (codePoint < 1114112) {
          if ((units -= 4) < 0) break;
          bytes.push(
            codePoint >> 18 | 240,
            codePoint >> 12 & 63 | 128,
            codePoint >> 6 & 63 | 128,
            codePoint & 63 | 128
          );
        } else {
          throw new Error("Invalid code point");
        }
      }
      return bytes;
    }
    function asciiToBytes(str) {
      const byteArray = [];
      for (let i2 = 0; i2 < str.length; ++i2) {
        byteArray.push(str.charCodeAt(i2) & 255);
      }
      return byteArray;
    }
    function utf16leToBytes(str, units) {
      let c, hi, lo;
      const byteArray = [];
      for (let i2 = 0; i2 < str.length; ++i2) {
        if ((units -= 2) < 0) break;
        c = str.charCodeAt(i2);
        hi = c >> 8;
        lo = c % 256;
        byteArray.push(lo);
        byteArray.push(hi);
      }
      return byteArray;
    }
    function base64ToBytes(str) {
      return base642.toByteArray(base64clean(str));
    }
    function blitBuffer(src, dst, offset, length) {
      let i2;
      for (i2 = 0; i2 < length; ++i2) {
        if (i2 + offset >= dst.length || i2 >= src.length) break;
        dst[i2 + offset] = src[i2];
      }
      return i2;
    }
    function isInstance(obj, type2) {
      return obj instanceof type2 || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type2.name;
    }
    function numberIsNaN(obj) {
      return obj !== obj;
    }
    const hexSliceLookupTable = (function() {
      const alphabet = "0123456789abcdef";
      const table = new Array(256);
      for (let i2 = 0; i2 < 16; ++i2) {
        const i16 = i2 * 16;
        for (let j = 0; j < 16; ++j) {
          table[i16 + j] = alphabet[i2] + alphabet[j];
        }
      }
      return table;
    })();
    function defineBigIntMethod(fn) {
      return typeof BigInt === "undefined" ? BufferBigIntNotDefined : fn;
    }
    function BufferBigIntNotDefined() {
      throw new Error("BigInt not supported");
    }
  })(buffer);
  const Buffer = buffer.Buffer;
  const sharp = {};
  const ONNX_NODE = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
    __proto__: null,
    default: sharp
  }, Symbol.toStringTag, { value: "Module" }));
  var ortWeb_min$1 = { exports: {} };
  const backends = {};
  const backendsSortedByPriority = [];
  const registerBackend = (name2, backend, priority) => {
    if (backend && typeof backend.init === "function" && typeof backend.createSessionHandler === "function") {
      const currentBackend = backends[name2];
      if (currentBackend === void 0) {
        backends[name2] = { backend, priority };
      } else if (currentBackend.priority > priority) {
        return;
      } else if (currentBackend.priority === priority) {
        if (currentBackend.backend !== backend) {
          throw new Error(`cannot register backend "${name2}" using priority ${priority}`);
        }
      }
      if (priority >= 0) {
        const i2 = backendsSortedByPriority.indexOf(name2);
        if (i2 !== -1) {
          backendsSortedByPriority.splice(i2, 1);
        }
        for (let i3 = 0; i3 < backendsSortedByPriority.length; i3++) {
          if (backends[backendsSortedByPriority[i3]].priority <= priority) {
            backendsSortedByPriority.splice(i3, 0, name2);
            return;
          }
        }
        backendsSortedByPriority.push(name2);
      }
      return;
    }
    throw new TypeError("not a valid backend");
  };
  const resolveBackend = (backendHints) => __async(null, null, function* () {
    const backendNames = backendHints.length === 0 ? backendsSortedByPriority : backendHints;
    const errors2 = [];
    for (const backendName of backendNames) {
      const backendInfo = backends[backendName];
      if (backendInfo) {
        if (backendInfo.initialized) {
          return backendInfo.backend;
        } else if (backendInfo.aborted) {
          continue;
        }
        const isInitializing = !!backendInfo.initPromise;
        try {
          if (!isInitializing) {
            backendInfo.initPromise = backendInfo.backend.init();
          }
          yield backendInfo.initPromise;
          backendInfo.initialized = true;
          return backendInfo.backend;
        } catch (e) {
          if (!isInitializing) {
            errors2.push({ name: backendName, err: e });
          }
          backendInfo.aborted = true;
        } finally {
          delete backendInfo.initPromise;
        }
      }
    }
    throw new Error(`no available backend found. ERR: ${errors2.map((e) => `[${e.name}] ${e.err}`).join(", ")}`);
  });
  class EnvImpl {
    constructor() {
      this.wasm = {};
      this.webgl = {};
      this.logLevelInternal = "warning";
    }
    // TODO standadize the getter and setter convention in env for other fields.
    set logLevel(value) {
      if (value === void 0) {
        return;
      }
      if (typeof value !== "string" || ["verbose", "info", "warning", "error", "fatal"].indexOf(value) === -1) {
        throw new Error(`Unsupported logging level: ${value}`);
      }
      this.logLevelInternal = value;
    }
    get logLevel() {
      return this.logLevelInternal;
    }
  }
  const env$2 = new EnvImpl();
  const isBigInt64ArrayAvailable = typeof BigInt64Array !== "undefined" && typeof BigInt64Array.from === "function";
  const isBigUint64ArrayAvailable = typeof BigUint64Array !== "undefined" && typeof BigUint64Array.from === "function";
  const 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]
  ]);
  const 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"]
  ]);
  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");
  }
  const calculateSize = (dims) => {
    let size = 1;
    for (let i2 = 0; i2 < dims.length; i2++) {
      const dim = dims[i2];
      if (typeof dim !== "number" || !Number.isSafeInteger(dim)) {
        throw new TypeError(`dims[${i2}] must be an integer, got: ${dim}`);
      }
      if (dim < 0) {
        throw new RangeError(`dims[${i2}] must be a non-negative integer, got: ${dim}`);
      }
      size *= dim;
    }
    return size;
  };
  let Tensor$2 = class Tensor2 {
    constructor(arg0, arg1, arg2) {
      let type2;
      let data;
      let dims;
      if (typeof arg0 === "string") {
        type2 = arg0;
        dims = 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)) {
            data = typedArrayConstructor.from(arg1);
          } else if (arg1 instanceof typedArrayConstructor) {
            data = arg1;
          } else {
            throw new TypeError(`A ${type2} tensor's data must be type of ${typedArrayConstructor}`);
          }
        }
      } else {
        dims = 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") {
            type2 = "string";
            data = arg0;
          } else if (firstElementType === "boolean") {
            type2 = "bool";
            data = Uint8Array.from(arg0);
          } else {
            throw new TypeError(`Invalid element type of data array: ${firstElementType}.`);
          }
        } else {
          const mappedType = NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(arg0.constructor);
          if (mappedType === void 0) {
            throw new TypeError(`Unsupported type for tensor data: ${arg0.constructor}.`);
          }
          type2 = mappedType;
          data = arg0;
        }
      }
      if (dims === void 0) {
        dims = [data.length];
      } else if (!Array.isArray(dims)) {
        throw new TypeError("A tensor's dims must be a number array");
      }
      const size = calculateSize(dims);
      if (size !== data.length) {
        throw new Error(`Tensor's size(${size}) does not match data length(${data.length}).`);
      }
      this.dims = dims;
      this.type = type2;
      this.data = data;
      this.size = size;
    }
    // #endregion
    /**
     * Create a new tensor object from image object
     *
     * @param buffer - Extracted image buffer data - assuming RGBA format
     * @param imageFormat - input image configuration - required configurations height, width, format
     * @param tensorFormat - output tensor configuration - Default is RGB format
     */
    static bufferToTensor(buffer2, options) {
      if (buffer2 === 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");
      }
      const { height, width } = options;
      const norm = options.norm;
      let normMean;
      let normBias;
      if (norm === void 0 || norm.mean === void 0) {
        normMean = 255;
      } else {
        normMean = norm.mean;
      }
      if (norm === void 0 || norm.bias === void 0) {
        normBias = 0;
      } else {
        normBias = norm.bias;
      }
      const inputformat = options.bitmapFormat !== void 0 ? options.bitmapFormat : "RGBA";
      const outputformat = options.tensorFormat !== void 0 ? options.tensorFormat !== void 0 ? options.tensorFormat : "RGB" : "RGB";
      const offset = height * width;
      const float32Data = outputformat === "RGBA" ? new Float32Array(offset * 4) : new Float32Array(offset * 3);
      let step = 4, rImagePointer = 0, gImagePointer = 1, bImagePointer = 2, aImagePointer = 3;
      let rTensorPointer = 0, gTensorPointer = offset, bTensorPointer = offset * 2, aTensorPointer = -1;
      if (inputformat === "RGB") {
        step = 3;
        rImagePointer = 0;
        gImagePointer = 1;
        bImagePointer = 2;
        aImagePointer = -1;
      }
      if (outputformat === "RGBA") {
        aTensorPointer = offset * 3;
      } else if (outputformat === "RBG") {
        rTensorPointer = 0;
        bTensorPointer = offset;
        gTensorPointer = offset * 2;
      } else if (outputformat === "BGR") {
        bTensorPointer = 0;
        gTensorPointer = offset;
        rTensorPointer = offset * 2;
      }
      for (let i2 = 0; i2 < offset; i2++, rImagePointer += step, bImagePointer += step, gImagePointer += step, aImagePointer += step) {
        float32Data[rTensorPointer++] = (buffer2[rImagePointer] + normBias) / normMean;
        float32Data[gTensorPointer++] = (buffer2[gImagePointer] + normBias) / normMean;
        float32Data[bTensorPointer++] = (buffer2[bImagePointer] + normBias) / normMean;
        if (aTensorPointer !== -1 && aImagePointer !== -1) {
          float32Data[aTensorPointer++] = (buffer2[aImagePointer] + normBias) / normMean;
        }
      }
      const outputTensor = outputformat === "RGBA" ? new Tensor2("float32", float32Data, [1, 4, height, width]) : new Tensor2("float32", float32Data, [1, 3, height, width]);
      return outputTensor;
    }
    static fromImage(image, options) {
      return __async(this, null, function* () {
        const isHTMLImageEle = typeof HTMLImageElement !== "undefined" && image instanceof HTMLImageElement;
        const isImageDataEle = typeof ImageData !== "undefined" && image instanceof ImageData;
        const isImageBitmap = typeof ImageBitmap !== "undefined" && image instanceof ImageBitmap;
        const isURL = typeof String !== "undefined" && (image instanceof String || typeof image === "string");
        let data;
        let tensorConfig = {};
        if (isHTMLImageEle) {
          const canvas = document.createElement("canvas");
          const pixels2DContext = canvas.getContext("2d");
          if (pixels2DContext != null) {
            let height = image.naturalHeight;
            let width = image.naturalWidth;
            if (options !== void 0 && options.resizedHeight !== void 0 && options.resizedWidth !== void 0) {
              height = options.resizedHeight;
              width = options.resizedWidth;
            }
            if (options !== void 0) {
              tensorConfig = options;
              if (options.tensorFormat !== void 0) {
                throw new Error("Image input config format must be RGBA for HTMLImageElement");
              } else {
                tensorConfig.tensorFormat = "RGBA";
              }
              if (options.height !== void 0 && options.height !== height) {
                throw new Error("Image input config height doesn't match HTMLImageElement height");
              } else {
                tensorConfig.height = height;
              }
              if (options.width !== void 0 && options.width !== width) {
                throw new Error("Image input config width doesn't match HTMLImageElement width");
              } else {
                tensorConfig.width = width;
              }
            } else {
              tensorConfig.tensorFormat = "RGBA";
              tensorConfig.height = height;
              tensorConfig.width = width;
            }
            canvas.width = width;
            canvas.height = height;
            pixels2DContext.drawImage(image, 0, 0, width, height);
            data = pixels2DContext.getImageData(0, 0, width, height).data;
          } else {
            throw new Error("Can not access image data");
          }
        } else if (isImageDataEle) {
          const format2 = "RGBA";
          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) {
            tensorConfig = options;
            if (options.bitmapFormat !== void 0 && options.bitmapFormat !== format2) {
              throw new Error("Image input config format must be RGBA for ImageData");
            } else {
              tensorConfig.bitmapFormat = "RGBA";
            }
          } else {
            tensorConfig.bitmapFormat = "RGBA";
          }
          tensorConfig.height = height;
          tensorConfig.width = width;
          if (options !== void 0) {
            const tempCanvas = document.createElement("canvas");
            tempCanvas.width = width;
            tempCanvas.height = height;
            const pixels2DContext = tempCanvas.getContext("2d");
            if (pixels2DContext != null) {
              pixels2DContext.putImageData(image, 0, 0);
              data = pixels2DContext.getImageData(0, 0, width, height).data;
            } else {
              throw new Error("Can not access image data");
            }
          } else {
            data = image.data;
          }
        } else if (isImageBitmap) {
          if (options === void 0) {
            throw new Error("Please provide image config with format for Imagebitmap");
          }
          if (options.bitmapFormat !== void 0) {
            throw new Error("Image input config format must be defined for ImageBitmap");
          }
          const pixels2DContext = document.createElement("canvas").getContext("2d");
          if (pixels2DContext != null) {
            const height = image.height;
            const width = image.width;
            pixels2DContext.drawImage(image, 0, 0, width, height);
            data = pixels2DContext.getImageData(0, 0, width, height).data;
            if (options !== void 0) {
              if (options.height !== void 0 && options.height !== height) {
                throw new Error("Image input config height doesn't match ImageBitmap height");
              } else {
                tensorConfig.height = height;
              }
              if (options.width !== void 0 && options.width !== width) {
                throw new Error("Image input config width doesn't match ImageBitmap width");
              } else {
                tensorConfig.width = width;
              }
            } else {
              tensorConfig.height = height;
              tensorConfig.width = width;
            }
            return Tensor2.bufferToTensor(data, tensorConfig);
          } else {
            throw new Error("Can not access image data");
          }
        } else if (isURL) {
          return new Promise((resolve2, reject) => {
            const canvas = document.createElement("canvas");
            const context = canvas.getContext("2d");
            if (!image || !context) {
              return reject();
            }
            const newImage = new Image();
            newImage.crossOrigin = "Anonymous";
            newImage.src = image;
            newImage.onload = () => {
              canvas.width = newImage.width;
              canvas.height = newImage.height;
              context.drawImage(newImage, 0, 0, canvas.width, canvas.height);
              const img = context.getImageData(0, 0, canvas.width, canvas.height);
              if (options !== void 0) {
                if (options.height !== void 0 && options.height !== canvas.height) {
                  throw new Error("Image input config height doesn't match ImageBitmap height");
                } else {
                  tensorConfig.height = canvas.height;
                }
                if (options.width !== void 0 && options.width !== canvas.width) {
                  throw new Error("Image input config width doesn't match ImageBitmap width");
                } else {
                  tensorConfig.width = canvas.width;
                }
              } else {
                tensorConfig.height = canvas.height;
                tensorConfig.width = canvas.width;
              }
              resolve2(Tensor2.bufferToTensor(img.data, tensorConfig));
            };
          });
        } else {
          throw new Error("Input data provided is not supported - aborted tensor creation");
        }
        if (data !== void 0) {
          return Tensor2.bufferToTensor(data, tensorConfig);
        } else {
          throw new Error("Input data provided is not supported - aborted tensor creation");
        }
      });
    }
    toImageData(options) {
      var _a3, _b2;
      const pixels2DContext = document.createElement("canvas").getContext("2d");
      let image;
      if (pixels2DContext != null) {
        const width = this.dims[3];
        const height = this.dims[2];
        const channels = this.dims[1];
        const inputformat = options !== void 0 ? options.format !== void 0 ? options.format : "RGB" : "RGB";
        const normMean = options !== void 0 ? ((_a3 = options.norm) === null || _a3 === void 0 ? void 0 : _a3.mean) !== void 0 ? options.norm.mean : 255 : 255;
        const normBias = options !== void 0 ? ((_b2 = options.norm) === null || _b2 === void 0 ? void 0 : _b2.bias) !== void 0 ? options.norm.bias : 0 : 0;
        const offset = height * width;
        if (options !== void 0) {
          if (options.height !== void 0 && options.height !== height) {
            throw new Error("Image output config height doesn't match tensor height");
          }
          if (options.width !== void 0 && options.width !== width) {
            throw new Error("Image output config width doesn't match tensor width");
          }
          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 = offset, bTensorPointer = offset * 2, aTensorPointer = -1;
        if (inputformat === "RGBA") {
          rTensorPointer = 0;
          gTensorPointer = offset;
          bTensorPointer = offset * 2;
          aTensorPointer = offset * 3;
        } else if (inputformat === "RGB") {
          rTensorPointer = 0;
          gTensorPointer = offset;
          bTensorPointer = offset * 2;
        } else if (inputformat === "RBG") {
          rTensorPointer = 0;
          bTensorPointer = offset;
          gTensorPointer = offset * 2;
        }
        image = pixels2DContext.createImageData(width, height);
        for (let i2 = 0; i2 < height * width; rImagePointer += step, gImagePointer += step, bImagePointer += step, aImagePointer += step, i2++) {
          image.data[rImagePointer] = (this.data[rTensorPointer++] - normBias) * normMean;
          image.data[gImagePointer] = (this.data[gTensorPointer++] - normBias) * normMean;
          image.data[bImagePointer] = (this.data[bTensorPointer++] - normBias) * normMean;
          image.data[aImagePointer] = aTensorPointer === -1 ? 255 : (this.data[aTensorPointer++] - normBias) * normMean;
        }
      } else {
        throw new Error("Can not access image data");
      }
      return image;
    }
    // #endregion
    // #region tensor utilities
    reshape(dims) {
      return new Tensor2(this.type, this.data, dims);
    }
  };
  const Tensor$1 = Tensor$2;
  let InferenceSession$2 = class InferenceSession2 {
    constructor(handler) {
      this.handler = handler;
    }
    run(feeds, arg1, arg2) {
      return __async(this, null, function* () {
        const fetches = {};
        let options = {};
        if (typeof feeds !== "object" || feeds === null || feeds instanceof Tensor$1 || 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 Tensor$1) {
            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 Tensor$1) {
                  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 = yield this.handler.run(feeds, fetches, options);
        const returnValue = {};
        for (const key in results) {
          if (Object.hasOwnProperty.call(results, key)) {
            returnValue[key] = new Tensor$1(results[key].type, results[key].data, results[key].dims);
          }
        }
        return returnValue;
      });
    }
    static create(arg0, arg1, arg2, arg3) {
      return __async(this, null, function* () {
        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 buffer2 = arg0;
          let byteOffset = 0;
          let byteLength2 = 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 >= buffer2.byteLength) {
              throw new RangeError(`'byteOffset' is out of range [0, ${buffer2.byteLength}).`);
            }
            byteLength2 = arg0.byteLength - byteOffset;
            if (typeof arg2 === "number") {
              byteLength2 = arg2;
              if (!Number.isSafeInteger(byteLength2)) {
                throw new RangeError("'byteLength' must be an integer.");
              }
              if (byteLength2 <= 0 || byteOffset + byteLength2 > buffer2.byteLength) {
                throw new RangeError(`'byteLength' is out of range (0, ${buffer2.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(buffer2, byteOffset, byteLength2);
        } else {
          throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");
        }
        const eps = options.executionProviders || [];
        const backendHints = eps.map((i2) => typeof i2 === "string" ? i2 : i2.name);
        const backend = yield resolveBackend(backendHints);
        const handler = yield backend.createSessionHandler(filePathOrUint8Array, options);
        return new InferenceSession2(handler);
      });
    }
    startProfiling() {
      this.handler.startProfiling();
    }
    endProfiling() {
      this.handler.endProfiling();
    }
    get inputNames() {
      return this.handler.inputNames;
    }
    get outputNames() {
      return this.handler.outputNames;
    }
  };
  const InferenceSession$1 = InferenceSession$2;
  const lib = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
    __proto__: null,
    InferenceSession: InferenceSession$1,
    Tensor: Tensor$1,
    env: env$2,
    registerBackend
  }, Symbol.toStringTag, { value: "Module" }));
  const require$$0 = /* @__PURE__ */ getAugmentedNamespace(lib);
  var hasRequiredOrtWeb_min;
  function requireOrtWeb_min() {
    if (hasRequiredOrtWeb_min) return ortWeb_min$1.exports;
    hasRequiredOrtWeb_min = 1;
    (function(module, exports$1) {
      !(function(t, e) {
        module.exports = e(require$$0);
      })(self, ((__WEBPACK_EXTERNAL_MODULE__1670__) => (() => {
        var __webpack_modules__ = { 3474: (t, e, n) => {
          var _scriptDir, r = (_scriptDir = (_scriptDir = "undefined" != typeof document && document.currentScript ? document.currentScript.src : void 0) || "/index.js", function(t2) {
            function e2() {
              return $.buffer != C && H($.buffer), F;
            }
            function r2() {
              return $.buffer != C && H($.buffer), N;
            }
            function i2() {
              return $.buffer != C && H($.buffer), L;
            }
            function o() {
              return $.buffer != C && H($.buffer), R;
            }
            function a() {
              return $.buffer != C && H($.buffer), j;
            }
            var s, u, c;
            t2 = t2 || {}, s || (s = void 0 !== t2 ? t2 : {}), s.ready = new Promise((function(t3, e3) {
              u = t3, c = e3;
            }));
            var l, p, f, d, h, g, b = Object.assign({}, s), m = "./this.program", y = (t3, e3) => {
              throw e3;
            }, _ = "object" == typeof window, v = "function" == typeof importScripts, w = "object" == typeof process$1 && "object" == typeof process$1.versions && "string" == typeof process$1.versions.node, x = s.ENVIRONMENT_IS_PTHREAD || false, T = "";
            function S(t3) {
              return s.locateFile ? s.locateFile(t3, T) : T + t3;
            }
            if (w) {
              let e3;
              T = v ? n(908).dirname(T) + "/" : "//", g = () => {
                h || (d = n(1384), h = n(908));
              }, l = function(t3, e4) {
                return g(), t3 = h.normalize(t3), d.readFileSync(t3, e4 ? void 0 : "utf8");
              }, f = (t3) => ((t3 = l(t3, true)).buffer || (t3 = new Uint8Array(t3)), t3), p = (t3, e4, n2) => {
                g(), t3 = h.normalize(t3), d.readFile(t3, (function(t4, r3) {
                  t4 ? n2(t4) : e4(r3.buffer);
                }));
              }, 1 < process$1.argv.length && (m = process$1.argv[1].replace(/\\/g, "/")), process$1.argv.slice(2), process$1.on("uncaughtException", (function(t3) {
                if (!(t3 instanceof ut)) throw t3;
              })), process$1.on("unhandledRejection", (function(t3) {
                throw t3;
              })), y = (t3, e4) => {
                if (J()) throw process$1.exitCode = t3, e4;
                e4 instanceof ut || P("exiting due to exception: " + e4), process$1.exit(t3);
              }, s.inspect = function() {
                return "[Emscripten Module object]";
              };
              try {
                e3 = n(9925);
              } catch (t3) {
                throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'), t3;
              }
              n.g.Worker = e3.Worker;
            } else (_ || v) && (v ? T = self.location.href : "undefined" != typeof document && document.currentScript && (T = document.currentScript.src), _scriptDir && (T = _scriptDir), T = 0 !== T.indexOf("blob:") ? T.substr(0, T.replace(/[?#].*/, "").lastIndexOf("/") + 1) : "", w || (l = (t3) => {
              var e3 = new XMLHttpRequest();
              return e3.open("GET", t3, false), e3.send(null), e3.responseText;
            }, v && (f = (t3) => {
              var e3 = new XMLHttpRequest();
              return e3.open("GET", t3, false), e3.responseType = "arraybuffer", e3.send(null), new Uint8Array(e3.response);
            }), p = (t3, e3, n2) => {
              var r3 = new XMLHttpRequest();
              r3.open("GET", t3, true), r3.responseType = "arraybuffer", r3.onload = () => {
                200 == r3.status || 0 == r3.status && r3.response ? e3(r3.response) : n2();
              }, r3.onerror = n2, r3.send(null);
            }));
            w && "undefined" == typeof performance && (n.g.performance = n(6953).performance);
            var O = console.log.bind(console), A = console.warn.bind(console);
            w && (g(), O = (t3) => d.writeSync(1, t3 + "\n"), A = (t3) => d.writeSync(2, t3 + "\n"));
            var E, I = s.print || O, P = s.printErr || A;
            Object.assign(s, b), b = null, s.thisProgram && (m = s.thisProgram), s.quit && (y = s.quit), s.wasmBinary && (E = s.wasmBinary);
            var D = s.noExitRuntime || false;
            "object" != typeof WebAssembly && it2("no native wasm support detected");
            var $, k, C, F, N, L, R, j, M = false, U = "undefined" != typeof TextDecoder ? new TextDecoder("utf8") : void 0;
            function V(t3, e3, n2) {
              var r3 = (e3 >>>= 0) + n2;
              for (n2 = e3; t3[n2] && !(n2 >= r3); ) ++n2;
              if (16 < n2 - e3 && t3.buffer && U) return U.decode(t3.buffer instanceof SharedArrayBuffer ? t3.slice(e3, n2) : t3.subarray(e3, n2));
              for (r3 = ""; e3 < n2; ) {
                var i3 = t3[e3++];
                if (128 & i3) {
                  var o2 = 63 & t3[e3++];
                  if (192 == (224 & i3)) r3 += String.fromCharCode((31 & i3) << 6 | o2);
                  else {
                    var a2 = 63 & t3[e3++];
                    65536 > (i3 = 224 == (240 & i3) ? (15 & i3) << 12 | o2 << 6 | a2 : (7 & i3) << 18 | o2 << 12 | a2 << 6 | 63 & t3[e3++]) ? r3 += String.fromCharCode(i3) : (i3 -= 65536, r3 += String.fromCharCode(55296 | i3 >> 10, 56320 | 1023 & i3));
                  }
                } else r3 += String.fromCharCode(i3);
              }
              return r3;
            }
            function B(t3, e3) {
              return (t3 >>>= 0) ? V(r2(), t3, e3) : "";
            }
            function z2(t3, e3, n2, r3) {
              if (!(0 < r3)) return 0;
              var i3 = n2 >>>= 0;
              r3 = n2 + r3 - 1;
              for (var o2 = 0; o2 < t3.length; ++o2) {
                var a2 = t3.charCodeAt(o2);
                if (55296 <= a2 && 57343 >= a2 && (a2 = 65536 + ((1023 & a2) << 10) | 1023 & t3.charCodeAt(++o2)), 127 >= a2) {
                  if (n2 >= r3) break;
                  e3[n2++ >>> 0] = a2;
                } else {
                  if (2047 >= a2) {
                    if (n2 + 1 >= r3) break;
                    e3[n2++ >>> 0] = 192 | a2 >> 6;
                  } else {
                    if (65535 >= a2) {
                      if (n2 + 2 >= r3) break;
                      e3[n2++ >>> 0] = 224 | a2 >> 12;
                    } else {
                      if (n2 + 3 >= r3) break;
                      e3[n2++ >>> 0] = 240 | a2 >> 18, e3[n2++ >>> 0] = 128 | a2 >> 12 & 63;
                    }
                    e3[n2++ >>> 0] = 128 | a2 >> 6 & 63;
                  }
                  e3[n2++ >>> 0] = 128 | 63 & a2;
                }
              }
              return e3[n2 >>> 0] = 0, n2 - i3;
            }
            function G(t3) {
              for (var e3 = 0, n2 = 0; n2 < t3.length; ++n2) {
                var r3 = t3.charCodeAt(n2);
                127 >= r3 ? e3++ : 2047 >= r3 ? e3 += 2 : 55296 <= r3 && 57343 >= r3 ? (e3 += 4, ++n2) : e3 += 3;
              }
              return e3;
            }
            function H(t3) {
              C = t3, s.HEAP8 = F = new Int8Array(t3), s.HEAP16 = new Int16Array(t3), s.HEAP32 = L = new Int32Array(t3), s.HEAPU8 = N = new Uint8Array(t3), s.HEAPU16 = new Uint16Array(t3), s.HEAPU32 = R = new Uint32Array(t3), s.HEAPF32 = new Float32Array(t3), s.HEAPF64 = j = new Float64Array(t3);
            }
            x && (C = s.buffer);
            var W = s.INITIAL_MEMORY || 16777216;
            if (x) $ = s.wasmMemory, C = s.buffer;
            else if (s.wasmMemory) $ = s.wasmMemory;
            else if (!(($ = new WebAssembly.Memory({ initial: W / 65536, maximum: 65536, shared: true })).buffer instanceof SharedArrayBuffer)) throw P("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"), w && console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"), Error("bad memory");
            $ && (C = $.buffer), W = C.byteLength, H(C);
            var q, X = [], Y = [], K = [], Z = [];
            function J() {
              return D || false;
            }
            function Q() {
              var t3 = s.preRun.shift();
              X.unshift(t3);
            }
            var tt, et = 0, rt = null;
            function it2(t3) {
              throw x ? postMessage({ cmd: "onAbort", arg: t3 }) : s.onAbort && s.onAbort(t3), P(t3 = "Aborted(" + t3 + ")"), M = true, t3 = new WebAssembly.RuntimeError(t3 + ". Build with -sASSERTIONS for more info."), c(t3), t3;
            }
            function ot() {
              return tt.startsWith("data:application/octet-stream;base64,");
            }
            function at() {
              var t3 = tt;
              try {
                if (t3 == tt && E) return new Uint8Array(E);
                if (f) return f(t3);
                throw "both async and sync fetching of the wasm failed";
              } catch (t4) {
                it2(t4);
              }
            }
            tt = "ort-wasm-threaded.wasm", ot() || (tt = S(tt));
            var st = {};
            function ut(t3) {
              this.name = "ExitStatus", this.message = "Program terminated with exit(" + t3 + ")", this.status = t3;
            }
            function ct(t3) {
              (t3 = dt.Vb[t3]) || it2(), dt.mc(t3);
            }
            function lt2(t3) {
              var e3 = dt.Cc();
              if (!e3) return 6;
              dt.ac.push(e3), dt.Vb[t3.Ub] = e3, e3.Ub = t3.Ub;
              var n2 = { cmd: "run", start_routine: t3.Ic, arg: t3.zc, pthread_ptr: t3.Ub };
              return e3.$b = () => {
                n2.time = performance.now(), e3.postMessage(n2, t3.Nc);
              }, e3.loaded && (e3.$b(), delete e3.$b), 0;
            }
            function pt2(t3) {
              if (x) return qt(1, 1, t3);
              J() || (dt.oc(), s.onExit && s.onExit(t3), M = true), y(t3, new ut(t3));
            }
            function ft(t3, e3) {
              if (!e3 && x) throw bt(t3), "unwind";
              J() || x || (me(), ht(K), be2(0), re[1].length && ie(1, 10), re[2].length && ie(2, 10), dt.oc()), pt2(t3);
            }
            var dt = { Yb: [], ac: [], qc: [], Vb: {}, fc: function() {
              x && dt.Ec();
            }, Pc: function() {
            }, Ec: function() {
              dt.receiveObjectTransfer = dt.Gc, dt.threadInitTLS = dt.pc, dt.setExitStatus = dt.nc, D = false;
            }, nc: function() {
            }, oc: function() {
              for (var t3 of Object.values(dt.Vb)) dt.mc(t3);
              for (t3 of dt.Yb) t3.terminate();
              dt.Yb = [];
            }, mc: function(t3) {
              var e3 = t3.Ub;
              delete dt.Vb[e3], dt.Yb.push(t3), dt.ac.splice(dt.ac.indexOf(t3), 1), t3.Ub = 0, xe(e3);
            }, Gc: function() {
            }, pc: function() {
              dt.qc.forEach(((t3) => t3()));
            }, Fc: function(t3, e3) {
              t3.onmessage = (n2) => {
                var r3 = (n2 = n2.data).cmd;
                if (t3.Ub && (dt.Bc = t3.Ub), n2.targetThread && n2.targetThread != de2()) {
                  var i3 = dt.Vb[n2.Qc];
                  i3 ? i3.postMessage(n2, n2.transferList) : P('Internal error! Worker sent a message "' + r3 + '" to target pthread ' + n2.targetThread + ", but that thread no longer exists!");
                } else "processProxyingQueue" === r3 ? Vt(n2.queue) : "spawnThread" === r3 ? lt2(n2) : "cleanupThread" === r3 ? ct(n2.thread) : "killThread" === r3 ? (n2 = n2.thread, r3 = dt.Vb[n2], delete dt.Vb[n2], r3.terminate(), xe(n2), dt.ac.splice(dt.ac.indexOf(r3), 1), r3.Ub = 0) : "cancelThread" === r3 ? dt.Vb[n2.thread].postMessage({ cmd: "cancel" }) : "loaded" === r3 ? (t3.loaded = true, e3 && e3(t3), t3.$b && (t3.$b(), delete t3.$b)) : "print" === r3 ? I("Thread " + n2.threadId + ": " + n2.text) : "printErr" === r3 ? P("Thread " + n2.threadId + ": " + n2.text) : "alert" === r3 ? alert("Thread " + n2.threadId + ": " + n2.text) : "setimmediate" === n2.target ? t3.postMessage(n2) : "onAbort" === r3 ? s.onAbort && s.onAbort(n2.arg) : r3 && P("worker sent an unknown command " + r3);
                dt.Bc = void 0;
              }, t3.onerror = (t4) => {
                throw P("worker sent an error! " + t4.filename + ":" + t4.lineno + ": " + t4.message), t4;
              }, w && (t3.on("message", (function(e4) {
                t3.onmessage({ data: e4 });
              })), t3.on("error", (function(e4) {
                t3.onerror(e4);
              })), t3.on("detachedExit", (function() {
              }))), t3.postMessage({ cmd: "load", urlOrBlob: s.mainScriptUrlOrBlob || _scriptDir, wasmMemory: $, wasmModule: k });
            }, yc: function() {
              var t3 = S("ort-wasm-threaded.worker.js");
              dt.Yb.push(new Worker(t3));
            }, Cc: function() {
              return 0 == dt.Yb.length && (dt.yc(), dt.Fc(dt.Yb[0])), dt.Yb.pop();
            } };
            function ht(t3) {
              for (; 0 < t3.length; ) t3.shift()(s);
            }
            function gt(t3) {
              var e3 = Ae();
              return t3 = t3(), Ee(e3), t3;
            }
            function bt(t3) {
              if (x) return qt(2, 0, t3);
              try {
                ft(t3);
              } catch (t4) {
                t4 instanceof ut || "unwind" == t4 || y(1, t4);
              }
            }
            s.PThread = dt, s.establishStackSpace = function() {
              var t3 = de2(), e3 = i2()[t3 + 44 >> 2 >>> 0];
              t3 = i2()[t3 + 48 >> 2 >>> 0], Oe(e3, e3 - t3), Ee(e3);
            };
            var mt = [];
            function yt(t3) {
              var e3 = mt[t3];
              return e3 || (t3 >= mt.length && (mt.length = t3 + 1), mt[t3] = e3 = q.get(t3)), e3;
            }
            s.invokeEntryPoint = function(t3, e3) {
              t3 = yt(t3)(e3), J() ? dt.nc(t3) : Te(t3);
            };
            var _t, vt, wt = [], xt = 0, Tt = 0;
            function St(t3) {
              this.Zb = t3, this.Sb = t3 - 24, this.xc = function(t4) {
                o()[this.Sb + 4 >> 2 >>> 0] = t4;
              }, this.bc = function() {
                return o()[this.Sb + 4 >> 2 >>> 0];
              }, this.wc = function(t4) {
                o()[this.Sb + 8 >> 2 >>> 0] = t4;
              }, this.Dc = function() {
                return o()[this.Sb + 8 >> 2 >>> 0];
              }, this.rc = function() {
                i2()[this.Sb >> 2 >>> 0] = 0;
              }, this.hc = function(t4) {
                t4 = t4 ? 1 : 0, e2()[this.Sb + 12 >> 0 >>> 0] = t4;
              }, this.uc = function() {
                return 0 != e2()[this.Sb + 12 >> 0 >>> 0];
              }, this.ic = function(t4) {
                t4 = t4 ? 1 : 0, e2()[this.Sb + 13 >> 0 >>> 0] = t4;
              }, this.kc = function() {
                return 0 != e2()[this.Sb + 13 >> 0 >>> 0];
              }, this.fc = function(t4, e3) {
                this.cc(0), this.xc(t4), this.wc(e3), this.rc(), this.hc(false), this.ic(false);
              }, this.sc = function() {
                Atomics.add(i2(), this.Sb >> 2, 1);
              }, this.Hc = function() {
                return 1 === Atomics.sub(i2(), this.Sb >> 2, 1);
              }, this.cc = function(t4) {
                o()[this.Sb + 16 >> 2 >>> 0] = t4;
              }, this.tc = function() {
                return o()[this.Sb + 16 >> 2 >>> 0];
              }, this.vc = function() {
                if (De(this.bc())) return o()[this.Zb >> 2 >>> 0];
                var t4 = this.tc();
                return 0 !== t4 ? t4 : this.Zb;
              };
            }
            function Ot(t3) {
              return ge(new St(t3).Sb);
            }
            function At(t3, e3, n2, r3) {
              return x ? qt(3, 1, t3, e3, n2, r3) : Et(t3, e3, n2, r3);
            }
            function Et(t3, e3, n2, r3) {
              if ("undefined" == typeof SharedArrayBuffer) return P("Current environment does not support SharedArrayBuffer, pthreads are not available!"), 6;
              var i3 = [];
              return x && 0 === i3.length ? At(t3, e3, n2, r3) : (t3 = { Ic: n2, Ub: t3, zc: r3, Nc: i3 }, x ? (t3.Oc = "spawnThread", postMessage(t3, i3), 0) : lt2(t3));
            }
            function It(t3, e3, n2) {
              return x ? qt(4, 1, t3, e3, n2) : 0;
            }
            function Pt(t3, e3) {
              if (x) return qt(5, 1, t3, e3);
            }
            function Dt(t3, e3) {
              if (x) return qt(6, 1, t3, e3);
            }
            function $t(t3, e3, n2) {
              if (x) return qt(7, 1, t3, e3, n2);
            }
            function kt(t3, e3, n2) {
              return x ? qt(8, 1, t3, e3, n2) : 0;
            }
            function Ct(t3, e3) {
              if (x) return qt(9, 1, t3, e3);
            }
            function Ft(t3, e3, n2) {
              if (x) return qt(10, 1, t3, e3, n2);
            }
            function Nt(t3, e3, n2, r3) {
              if (x) return qt(11, 1, t3, e3, n2, r3);
            }
            function Lt(t3, e3, n2, r3) {
              if (x) return qt(12, 1, t3, e3, n2, r3);
            }
            function Rt(t3, e3, n2, r3) {
              if (x) return qt(13, 1, t3, e3, n2, r3);
            }
            function jt(t3) {
              if (x) return qt(14, 1, t3);
            }
            function Mt(t3, e3) {
              if (x) return qt(15, 1, t3, e3);
            }
            function Ut(t3, e3, n2) {
              if (x) return qt(16, 1, t3, e3, n2);
            }
            function Vt(t3) {
              Atomics.store(i2(), t3 >> 2, 1), de2() && we(t3), Atomics.compareExchange(i2(), t3 >> 2, 1, 0);
            }
            function Bt(t3) {
              return o()[t3 >>> 2] + 4294967296 * i2()[t3 + 4 >>> 2];
            }
            function zt(t3, e3, n2, r3, i3, o2) {
              return x ? qt(17, 1, t3, e3, n2, r3, i3, o2) : -52;
            }
            function Gt(t3, e3, n2, r3, i3, o2) {
              if (x) return qt(18, 1, t3, e3, n2, r3, i3, o2);
            }
            function Ht(t3) {
              var n2 = G(t3) + 1, r3 = he2(n2);
              return r3 && z2(t3, e2(), r3, n2), r3;
            }
            function Wt(t3, e3, n2) {
              function r3(t4) {
                return (t4 = t4.toTimeString().match(/\(([A-Za-z ]+)\)$/)) ? t4[1] : "GMT";
              }
              if (x) return qt(19, 1, t3, e3, n2);
              var a2 = (/* @__PURE__ */ new Date()).getFullYear(), s2 = new Date(a2, 0, 1), u2 = new Date(a2, 6, 1);
              a2 = s2.getTimezoneOffset();
              var c2 = u2.getTimezoneOffset(), l2 = Math.max(a2, c2);
              i2()[t3 >> 2 >>> 0] = 60 * l2, i2()[e3 >> 2 >>> 0] = Number(a2 != c2), t3 = r3(s2), e3 = r3(u2), t3 = Ht(t3), e3 = Ht(e3), c2 < a2 ? (o()[n2 >> 2 >>> 0] = t3, o()[n2 + 4 >> 2 >>> 0] = e3) : (o()[n2 >> 2 >>> 0] = e3, o()[n2 + 4 >> 2 >>> 0] = t3);
            }
            function qt(t3, e3) {
              var n2 = arguments.length - 2, r3 = arguments;
              return gt((() => {
                for (var i3 = Ie(8 * n2), o2 = i3 >> 3, s2 = 0; s2 < n2; s2++) {
                  var u2 = r3[2 + s2];
                  a()[o2 + s2 >>> 0] = u2;
                }
                return ve(t3, n2, i3, e3);
              }));
            }
            s.executeNotifiedProxyingQueue = Vt, vt = w ? () => {
              var t3 = process$1.hrtime();
              return 1e3 * t3[0] + t3[1] / 1e6;
            } : x ? () => performance.now() - s.__performance_now_clock_drift : () => performance.now();
            var Xt, Yt = [], Kt = {};
            function Zt() {
              if (!Xt) {
                var t3, e3 = { USER: "web_user", LOGNAME: "web_user", PATH: "/", PWD: "/", HOME: "/home/web_user", LANG: ("object" == typeof navigator && navigator.languages && navigator.languages[0] || "C").replace("-", "_") + ".UTF-8", _: m || "./this.program" };
                for (t3 in Kt) void 0 === Kt[t3] ? delete e3[t3] : e3[t3] = Kt[t3];
                var n2 = [];
                for (t3 in e3) n2.push(t3 + "=" + e3[t3]);
                Xt = n2;
              }
              return Xt;
            }
            function Jt(t3, n2) {
              if (x) return qt(20, 1, t3, n2);
              var r3 = 0;
              return Zt().forEach((function(i3, a2) {
                var s2 = n2 + r3;
                for (a2 = o()[t3 + 4 * a2 >> 2 >>> 0] = s2, s2 = 0; s2 < i3.length; ++s2) e2()[a2++ >> 0 >>> 0] = i3.charCodeAt(s2);
                e2()[a2 >> 0 >>> 0] = 0, r3 += i3.length + 1;
              })), 0;
            }
            function Qt(t3, e3) {
              if (x) return qt(21, 1, t3, e3);
              var n2 = Zt();
              o()[t3 >> 2 >>> 0] = n2.length;
              var r3 = 0;
              return n2.forEach((function(t4) {
                r3 += t4.length + 1;
              })), o()[e3 >> 2 >>> 0] = r3, 0;
            }
            function te(t3) {
              return x ? qt(22, 1, t3) : 52;
            }
            function ee(t3, e3, n2, r3) {
              return x ? qt(23, 1, t3, e3, n2, r3) : 52;
            }
            function ne(t3, e3, n2, r3, i3) {
              return x ? qt(24, 1, t3, e3, n2, r3, i3) : 70;
            }
            var re = [null, [], []];
            function ie(t3, e3) {
              var n2 = re[t3];
              0 === e3 || 10 === e3 ? ((1 === t3 ? I : P)(V(n2, 0)), n2.length = 0) : n2.push(e3);
            }
            function oe(t3, e3, n2, i3) {
              if (x) return qt(25, 1, t3, e3, n2, i3);
              for (var a2 = 0, s2 = 0; s2 < n2; s2++) {
                var u2 = o()[e3 >> 2 >>> 0], c2 = o()[e3 + 4 >> 2 >>> 0];
                e3 += 8;
                for (var l2 = 0; l2 < c2; l2++) ie(t3, r2()[u2 + l2 >>> 0]);
                a2 += c2;
              }
              return o()[i3 >> 2 >>> 0] = a2, 0;
            }
            var ae = 0;
            function se(t3) {
              return 0 == t3 % 4 && (0 != t3 % 100 || 0 == t3 % 400);
            }
            var ue = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], ce = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
            function le(t3, n2, r3, o2) {
              function a2(t4, e3, n3) {
                for (t4 = "number" == typeof t4 ? t4.toString() : t4 || ""; t4.length < e3; ) t4 = n3[0] + t4;
                return t4;
              }
              function s2(t4, e3) {
                return a2(t4, e3, "0");
              }
              function u2(t4, e3) {
                function n3(t5) {
                  return 0 > t5 ? -1 : 0 < t5 ? 1 : 0;
                }
                var r4;
                return 0 === (r4 = n3(t4.getFullYear() - e3.getFullYear())) && 0 === (r4 = n3(t4.getMonth() - e3.getMonth())) && (r4 = n3(t4.getDate() - e3.getDate())), r4;
              }
              function c2(t4) {
                switch (t4.getDay()) {
                  case 0:
                    return new Date(t4.getFullYear() - 1, 11, 29);
                  case 1:
                    return t4;
                  case 2:
                    return new Date(t4.getFullYear(), 0, 3);
                  case 3:
                    return new Date(t4.getFullYear(), 0, 2);
                  case 4:
                    return new Date(t4.getFullYear(), 0, 1);
                  case 5:
                    return new Date(t4.getFullYear() - 1, 11, 31);
                  case 6:
                    return new Date(t4.getFullYear() - 1, 11, 30);
                }
              }
              function l2(t4) {
                var e3 = t4.Wb;
                for (t4 = new Date(new Date(t4.Xb + 1900, 0, 1).getTime()); 0 < e3; ) {
                  var n3 = t4.getMonth(), r4 = (se(t4.getFullYear()) ? ue : ce)[n3];
                  if (!(e3 > r4 - t4.getDate())) {
                    t4.setDate(t4.getDate() + e3);
                    break;
                  }
                  e3 -= r4 - t4.getDate() + 1, t4.setDate(1), 11 > n3 ? t4.setMonth(n3 + 1) : (t4.setMonth(0), t4.setFullYear(t4.getFullYear() + 1));
                }
                return n3 = new Date(t4.getFullYear() + 1, 0, 4), e3 = c2(new Date(t4.getFullYear(), 0, 4)), n3 = c2(n3), 0 >= u2(e3, t4) ? 0 >= u2(n3, t4) ? t4.getFullYear() + 1 : t4.getFullYear() : t4.getFullYear() - 1;
              }
              var p2 = i2()[o2 + 40 >> 2 >>> 0];
              for (var f2 in o2 = { Lc: i2()[o2 >> 2 >>> 0], Kc: i2()[o2 + 4 >> 2 >>> 0], dc: i2()[o2 + 8 >> 2 >>> 0], jc: i2()[o2 + 12 >> 2 >>> 0], ec: i2()[o2 + 16 >> 2 >>> 0], Xb: i2()[o2 + 20 >> 2 >>> 0], Tb: i2()[o2 + 24 >> 2 >>> 0], Wb: i2()[o2 + 28 >> 2 >>> 0], Rc: i2()[o2 + 32 >> 2 >>> 0], Jc: i2()[o2 + 36 >> 2 >>> 0], Mc: p2 ? B(p2) : "" }, r3 = B(r3), p2 = { "%c": "%a %b %d %H:%M:%S %Y", "%D": "%m/%d/%y", "%F": "%Y-%m-%d", "%h": "%b", "%r": "%I:%M:%S %p", "%R": "%H:%M", "%T": "%H:%M:%S", "%x": "%m/%d/%y", "%X": "%H:%M:%S", "%Ec": "%c", "%EC": "%C", "%Ex": "%m/%d/%y", "%EX": "%H:%M:%S", "%Ey": "%y", "%EY": "%Y", "%Od": "%d", "%Oe": "%e", "%OH": "%H", "%OI": "%I", "%Om": "%m", "%OM": "%M", "%OS": "%S", "%Ou": "%u", "%OU": "%U", "%OV": "%V", "%Ow": "%w", "%OW": "%W", "%Oy": "%y" }) r3 = r3.replace(new RegExp(f2, "g"), p2[f2]);
              var d2 = "Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "), h2 = "January February March April May June July August September October November December".split(" ");
              for (f2 in p2 = { "%a": function(t4) {
                return d2[t4.Tb].substring(0, 3);
              }, "%A": function(t4) {
                return d2[t4.Tb];
              }, "%b": function(t4) {
                return h2[t4.ec].substring(0, 3);
              }, "%B": function(t4) {
                return h2[t4.ec];
              }, "%C": function(t4) {
                return s2((t4.Xb + 1900) / 100 | 0, 2);
              }, "%d": function(t4) {
                return s2(t4.jc, 2);
              }, "%e": function(t4) {
                return a2(t4.jc, 2, " ");
              }, "%g": function(t4) {
                return l2(t4).toString().substring(2);
              }, "%G": function(t4) {
                return l2(t4);
              }, "%H": function(t4) {
                return s2(t4.dc, 2);
              }, "%I": function(t4) {
                return 0 == (t4 = t4.dc) ? t4 = 12 : 12 < t4 && (t4 -= 12), s2(t4, 2);
              }, "%j": function(t4) {
                for (var e3 = 0, n3 = 0; n3 <= t4.ec - 1; e3 += (se(t4.Xb + 1900) ? ue : ce)[n3++]) ;
                return s2(t4.jc + e3, 3);
              }, "%m": function(t4) {
                return s2(t4.ec + 1, 2);
              }, "%M": function(t4) {
                return s2(t4.Kc, 2);
              }, "%n": function() {
                return "\n";
              }, "%p": function(t4) {
                return 0 <= t4.dc && 12 > t4.dc ? "AM" : "PM";
              }, "%S": function(t4) {
                return s2(t4.Lc, 2);
              }, "%t": function() {
                return "	";
              }, "%u": function(t4) {
                return t4.Tb || 7;
              }, "%U": function(t4) {
                return s2(Math.floor((t4.Wb + 7 - t4.Tb) / 7), 2);
              }, "%V": function(t4) {
                var e3 = Math.floor((t4.Wb + 7 - (t4.Tb + 6) % 7) / 7);
                if (2 >= (t4.Tb + 371 - t4.Wb - 2) % 7 && e3++, e3) 53 == e3 && (4 == (n3 = (t4.Tb + 371 - t4.Wb) % 7) || 3 == n3 && se(t4.Xb) || (e3 = 1));
                else {
                  e3 = 52;
                  var n3 = (t4.Tb + 7 - t4.Wb - 1) % 7;
                  (4 == n3 || 5 == n3 && se(t4.Xb % 400 - 1)) && e3++;
                }
                return s2(e3, 2);
              }, "%w": function(t4) {
                return t4.Tb;
              }, "%W": function(t4) {
                return s2(Math.floor((t4.Wb + 7 - (t4.Tb + 6) % 7) / 7), 2);
              }, "%y": function(t4) {
                return (t4.Xb + 1900).toString().substring(2);
              }, "%Y": function(t4) {
                return t4.Xb + 1900;
              }, "%z": function(t4) {
                var e3 = 0 <= (t4 = t4.Jc);
                return t4 = Math.abs(t4) / 60, (e3 ? "+" : "-") + String("0000" + (t4 / 60 * 100 + t4 % 60)).slice(-4);
              }, "%Z": function(t4) {
                return t4.Mc;
              }, "%%": function() {
                return "%";
              } }, r3 = r3.replace(/%%/g, "\0\0"), p2) r3.includes(f2) && (r3 = r3.replace(new RegExp(f2, "g"), p2[f2](o2)));
              return f2 = (function(t4) {
                var e3 = Array(G(t4) + 1);
                return z2(t4, e3, 0, e3.length), e3;
              })(r3 = r3.replace(/\0\0/g, "%")), f2.length > n2 ? 0 : ((function(t4, n3) {
                e2().set(t4, n3 >>> 0);
              })(f2, t3), f2.length - 1);
            }
            dt.fc();
            var pe = [null, pt2, bt, At, It, Pt, Dt, $t, kt, Ct, Ft, Nt, Lt, Rt, jt, Mt, Ut, zt, Gt, Wt, Jt, Qt, te, ee, ne, oe], fe = { b: function(t3) {
              return he2(t3 + 24) + 24;
            }, n: function(t3) {
              return (t3 = new St(t3)).uc() || (t3.hc(true), xt--), t3.ic(false), wt.push(t3), t3.sc(), t3.vc();
            }, ma: function(t3) {
              throw P("Unexpected exception thrown, this is not properly supported - aborting"), M = true, t3;
            }, x: function() {
              Se(0);
              var t3 = wt.pop();
              if (t3.Hc() && !t3.kc()) {
                var e3 = t3.Dc();
                e3 && yt(e3)(t3.Zb), Ot(t3.Zb);
              }
              Tt = 0;
            }, e: function() {
              var t3 = Tt;
              if (!t3) return ae = 0;
              var e3 = new St(t3);
              e3.cc(t3);
              var n2 = e3.bc();
              if (!n2) return ae = 0, t3;
              for (var r3 = Array.prototype.slice.call(arguments), i3 = 0; i3 < r3.length; i3++) {
                var o2 = r3[i3];
                if (0 === o2 || o2 === n2) break;
                if (Pe(o2, n2, e3.Sb + 16)) return ae = o2, t3;
              }
              return ae = n2, t3;
            }, l: function() {
              var t3 = Tt;
              if (!t3) return ae = 0;
              var e3 = new St(t3);
              e3.cc(t3);
              var n2 = e3.bc();
              if (!n2) return ae = 0, t3;
              for (var r3 = Array.prototype.slice.call(arguments), i3 = 0; i3 < r3.length; i3++) {
                var o2 = r3[i3];
                if (0 === o2 || o2 === n2) break;
                if (Pe(o2, n2, e3.Sb + 16)) return ae = o2, t3;
              }
              return ae = n2, t3;
            }, h: function() {
              var t3 = Tt;
              if (!t3) return ae = 0;
              var e3 = new St(t3);
              e3.cc(t3);
              var n2 = e3.bc();
              if (!n2) return ae = 0, t3;
              for (var r3 = Array.prototype.slice.call(arguments), i3 = 0; i3 < r3.length; i3++) {
                var o2 = r3[i3];
                if (0 === o2 || o2 === n2) break;
                if (Pe(o2, n2, e3.Sb + 16)) return ae = o2, t3;
              }
              return ae = n2, t3;
            }, t: Ot, M: function() {
              var t3 = wt.pop();
              t3 || it2("no exception to throw");
              var e3 = t3.Zb;
              throw t3.kc() || (wt.push(t3), t3.ic(true), t3.hc(false), xt++), Tt = e3, e3;
            }, c: function(t3, e3, n2) {
              throw new St(t3).fc(e3, n2), Tt = t3, xt++, t3;
            }, pa: function() {
              return xt;
            }, Fa: function(t3) {
              ye(t3, !v, 1, !_), dt.pc();
            }, T: function(t3) {
              x ? postMessage({ cmd: "cleanupThread", thread: t3 }) : ct(t3);
            }, xa: Et, j: function(t3) {
              throw Tt || (Tt = t3), t3;
            }, H: It, Ma: Pt, ua: Dt, wa: $t, oa: kt, Ka: Ct, Ca: Ft, Ja: Nt, V: Lt, va: Rt, sa: jt, La: Mt, ta: Ut, Ta: function() {
            }, X: function() {
              it2("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking");
            }, Ua: function() {
              it2("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking");
            }, W: function() {
              return Date.now();
            }, ya: function() {
              return 2097152;
            }, Oa: function() {
              return true;
            }, za: function(t3, e3, n2, r3) {
              if (t3 == e3) setTimeout((() => Vt(r3)));
              else if (x) postMessage({ targetThread: t3, cmd: "processProxyingQueue", queue: r3 });
              else {
                if (!(t3 = dt.Vb[t3])) return;
                t3.postMessage({ cmd: "processProxyingQueue", queue: r3 });
              }
              return 1;
            }, Ea: function() {
              return -1;
            }, Pa: function(t3, e3) {
              t3 = new Date(1e3 * Bt(t3)), i2()[e3 >> 2 >>> 0] = t3.getUTCSeconds(), i2()[e3 + 4 >> 2 >>> 0] = t3.getUTCMinutes(), i2()[e3 + 8 >> 2 >>> 0] = t3.getUTCHours(), i2()[e3 + 12 >> 2 >>> 0] = t3.getUTCDate(), i2()[e3 + 16 >> 2 >>> 0] = t3.getUTCMonth(), i2()[e3 + 20 >> 2 >>> 0] = t3.getUTCFullYear() - 1900, i2()[e3 + 24 >> 2 >>> 0] = t3.getUTCDay(), t3 = (t3.getTime() - Date.UTC(t3.getUTCFullYear(), 0, 1, 0, 0, 0, 0)) / 864e5 | 0, i2()[e3 + 28 >> 2 >>> 0] = t3;
            }, Qa: function(t3, e3) {
              t3 = new Date(1e3 * Bt(t3)), i2()[e3 >> 2 >>> 0] = t3.getSeconds(), i2()[e3 + 4 >> 2 >>> 0] = t3.getMinutes(), i2()[e3 + 8 >> 2 >>> 0] = t3.getHours(), i2()[e3 + 12 >> 2 >>> 0] = t3.getDate(), i2()[e3 + 16 >> 2 >>> 0] = t3.getMonth(), i2()[e3 + 20 >> 2 >>> 0] = t3.getFullYear() - 1900, i2()[e3 + 24 >> 2 >>> 0] = t3.getDay();
              var n2 = new Date(t3.getFullYear(), 0, 1), r3 = (t3.getTime() - n2.getTime()) / 864e5 | 0;
              i2()[e3 + 28 >> 2 >>> 0] = r3, i2()[e3 + 36 >> 2 >>> 0] = -60 * t3.getTimezoneOffset(), r3 = new Date(t3.getFullYear(), 6, 1).getTimezoneOffset(), t3 = 0 | (r3 != (n2 = n2.getTimezoneOffset()) && t3.getTimezoneOffset() == Math.min(n2, r3)), i2()[e3 + 32 >> 2 >>> 0] = t3;
            }, Ra: function(t3) {
              var e3 = new Date(i2()[t3 + 20 >> 2 >>> 0] + 1900, i2()[t3 + 16 >> 2 >>> 0], i2()[t3 + 12 >> 2 >>> 0], i2()[t3 + 8 >> 2 >>> 0], i2()[t3 + 4 >> 2 >>> 0], i2()[t3 >> 2 >>> 0], 0), n2 = i2()[t3 + 32 >> 2 >>> 0], r3 = e3.getTimezoneOffset(), o2 = new Date(e3.getFullYear(), 0, 1), a2 = new Date(e3.getFullYear(), 6, 1).getTimezoneOffset(), s2 = o2.getTimezoneOffset(), u2 = Math.min(s2, a2);
              return 0 > n2 ? i2()[t3 + 32 >> 2 >>> 0] = Number(a2 != s2 && u2 == r3) : 0 < n2 != (u2 == r3) && (a2 = Math.max(s2, a2), e3.setTime(e3.getTime() + 6e4 * ((0 < n2 ? u2 : a2) - r3))), i2()[t3 + 24 >> 2 >>> 0] = e3.getDay(), n2 = (e3.getTime() - o2.getTime()) / 864e5 | 0, i2()[t3 + 28 >> 2 >>> 0] = n2, i2()[t3 >> 2 >>> 0] = e3.getSeconds(), i2()[t3 + 4 >> 2 >>> 0] = e3.getMinutes(), i2()[t3 + 8 >> 2 >>> 0] = e3.getHours(), i2()[t3 + 12 >> 2 >>> 0] = e3.getDate(), i2()[t3 + 16 >> 2 >>> 0] = e3.getMonth(), e3.getTime() / 1e3 | 0;
            }, Aa: zt, Ba: Gt, Sa: function t3(e3, n2, r3) {
              t3.Ac || (t3.Ac = true, Wt(e3, n2, r3));
            }, y: function() {
              it2("");
            }, U: function() {
              if (!w && !v) {
                var t3 = "Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread";
                _t || (_t = {}), _t[t3] || (_t[t3] = 1, w && (t3 = "warning: " + t3), P(t3));
              }
            }, ra: function() {
              return 4294901760;
            }, B: vt, Ia: function(t3, e3, n2) {
              r2().copyWithin(t3 >>> 0, e3 >>> 0, e3 + n2 >>> 0);
            }, F: function() {
              return w ? n(3993).cpus().length : navigator.hardwareConcurrency;
            }, Da: function(t3, e3, n2) {
              Yt.length = e3, n2 >>= 3;
              for (var r3 = 0; r3 < e3; r3++) Yt[r3] = a()[n2 + r3 >>> 0];
              return (0 > t3 ? st[-t3 - 1] : pe[t3]).apply(null, Yt);
            }, qa: function(t3) {
              var e3 = r2().length;
              if ((t3 >>>= 0) <= e3 || 4294901760 < t3) return false;
              for (var n2 = 1; 4 >= n2; n2 *= 2) {
                var i3 = e3 * (1 + 0.2 / n2);
                i3 = Math.min(i3, t3 + 100663296);
                var o2 = Math;
                i3 = Math.max(t3, i3), o2 = o2.min.call(o2, 4294901760, i3 + (65536 - i3 % 65536) % 65536);
                t: {
                  try {
                    $.grow(o2 - C.byteLength + 65535 >>> 16), H($.buffer);
                    var a2 = 1;
                    break t;
                  } catch (t4) {
                  }
                  a2 = void 0;
                }
                if (a2) return true;
              }
              return false;
            }, Na: function() {
              throw "unwind";
            }, Ga: Jt, Ha: Qt, J: ft, I: te, S: ee, ga: ne, R: oe, d: function() {
              return ae;
            }, na: function t3(r3, i3) {
              t3.lc || (t3.lc = (function() {
                if ("object" == typeof crypto && "function" == typeof crypto.getRandomValues) {
                  var t4 = new Uint8Array(1);
                  return () => (crypto.getRandomValues(t4), t4[0]);
                }
                if (w) try {
                  var e3 = n(Object((function() {
                    var t5 = new Error("Cannot find module 'crypto'");
                    throw t5.code = "MODULE_NOT_FOUND", t5;
                  })()));
                  return () => e3.randomBytes(1)[0];
                } catch (t5) {
                }
                return () => it2("randomDevice");
              })());
              for (var o2 = 0; o2 < i3; o2++) e2()[r3 + o2 >> 0 >>> 0] = t3.lc();
              return 0;
            }, ia: function(t3, e3, n2) {
              var r3 = Ae();
              try {
                return yt(t3)(e3, n2);
              } catch (t4) {
                if (Ee(r3), t4 !== t4 + 0) throw t4;
                Se(1, 0);
              }
            }, ja: function(t3, e3, n2) {
              var r3 = Ae();
              try {
                return yt(t3)(e3, n2);
              } catch (t4) {
                if (Ee(r3), t4 !== t4 + 0) throw t4;
                Se(1, 0);
              }
            }, K: function(t3) {
              var e3 = Ae();
              try {
                return yt(t3)();
              } catch (t4) {
                if (Ee(e3), t4 !== t4 + 0) throw t4;
                Se(1, 0);
              }
            }, f: function(t3, e3) {
              var n2 = Ae();
              try {
                return yt(t3)(e3);
              } catch (t4) {
                if (Ee(n2), t4 !== t4 + 0) throw t4;
                Se(1, 0);
              }
            }, P: function(t3, e3, n2) {
              var r3 = Ae();
              try {
                return yt(t3)(e3, n2);
              } catch (t4) {
                if (Ee(r3), t4 !== t4 + 0) throw t4;
                Se(1, 0);
              }
            }, Q: function(t3, e3, n2) {
              var r3 = Ae();
              try {
                return yt(t3)(e3, n2);
              } catch (t4) {
                if (Ee(r3), t4 !== t4 + 0) throw t4;
                Se(1, 0);
              }
            }, k: function(t3, e3, n2) {
              var r3 = Ae();
              try {
                return yt(t3)(e3, n2);
              } catch (t4) {
                if (Ee(r3), t4 !== t4 + 0) throw t4;
                Se(1, 0);
              }
            }, p: function(t3, e3, n2, r3) {
              var i3 = Ae();
              try {
                return yt(t3)(e3, n2, r3);
              } catch (t4) {
                if (Ee(i3), t4 !== t4 + 0) throw t4;
                Se(1, 0);
              }
            }, q: function(t3, e3, n2, r3, i3) {
              var o2 = Ae();
              try {
                return yt(t3)(e3, n2, r3, i3);
              } catch (t4) {
                if (Ee(o2), t4 !== t4 + 0) throw t4;
                Se(1, 0);
              }
            }, N: function(t3, e3, n2, r3, i3, o2) {
              var a2 = Ae();
              try {
                return yt(t3)(e3, n2, r3, i3, o2);
              } catch (t4) {
                if (Ee(a2), t4 !== t4 + 0) throw t4;
                Se(1, 0);
              }
            }, s: function(t3, e3, n2, r3, i3, o2) {
              var a2 = Ae();
              try {
                return yt(t3)(e3, n2, r3, i3, o2);
              } catch (t4) {
                if (Ee(a2), t4 !== t4 + 0) throw t4;
                Se(1, 0);
              }
            }, w: function(t3, e3, n2, r3, i3, o2, a2) {
              var s2 = Ae();
              try {
                return yt(t3)(e3, n2, r3, i3, o2, a2);
              } catch (t4) {
                if (Ee(s2), t4 !== t4 + 0) throw t4;
                Se(1, 0);
              }
            }, L: function(t3, e3, n2, r3, i3, o2, a2, s2) {
              var u2 = Ae();
              try {
                return yt(t3)(e3, n2, r3, i3, o2, a2, s2);
              } catch (t4) {
                if (Ee(u2), t4 !== t4 + 0) throw t4;
                Se(1, 0);
              }
            }, E: function(t3, e3, n2, r3, i3, o2, a2, s2, u2, c2, l2, p2) {
              var f2 = Ae();
              try {
                return yt(t3)(e3, n2, r3, i3, o2, a2, s2, u2, c2, l2, p2);
              } catch (t4) {
                if (Ee(f2), t4 !== t4 + 0) throw t4;
                Se(1, 0);
              }
            }, aa: function(t3, e3, n2, r3, i3, o2, a2, s2) {
              var u2 = Ae();
              try {
                return Me(t3, e3, n2, r3, i3, o2, a2, s2);
              } catch (t4) {
                if (Ee(u2), t4 !== t4 + 0) throw t4;
                Se(1, 0);
              }
            }, _: function(t3, e3, n2, r3, i3, o2, a2) {
              var s2 = Ae();
              try {
                return ke(t3, e3, n2, r3, i3, o2, a2);
              } catch (t4) {
                if (Ee(s2), t4 !== t4 + 0) throw t4;
                Se(1, 0);
              }
            }, Z: function(t3, e3, n2, r3, i3) {
              var o2 = Ae();
              try {
                return Ue(t3, e3, n2, r3, i3);
              } catch (t4) {
                if (Ee(o2), t4 !== t4 + 0) throw t4;
                Se(1, 0);
              }
            }, ca: function(t3, e3, n2, r3) {
              var i3 = Ae();
              try {
                return Re(t3, e3, n2, r3);
              } catch (t4) {
                if (Ee(i3), t4 !== t4 + 0) throw t4;
                Se(1, 0);
              }
            }, $: function(t3) {
              var e3 = Ae();
              try {
                return $e(t3);
              } catch (t4) {
                if (Ee(e3), t4 !== t4 + 0) throw t4;
                Se(1, 0);
              }
            }, ba: function(t3, e3) {
              var n2 = Ae();
              try {
                return je(t3, e3);
              } catch (t4) {
                if (Ee(n2), t4 !== t4 + 0) throw t4;
                Se(1, 0);
              }
            }, Y: function(t3, e3, n2) {
              var r3 = Ae();
              try {
                return Ce(t3, e3, n2);
              } catch (t4) {
                if (Ee(r3), t4 !== t4 + 0) throw t4;
                Se(1, 0);
              }
            }, g: function(t3) {
              var e3 = Ae();
              try {
                yt(t3)();
              } catch (t4) {
                if (Ee(e3), t4 !== t4 + 0) throw t4;
                Se(1, 0);
              }
            }, r: function(t3, e3) {
              var n2 = Ae();
              try {
                yt(t3)(e3);
              } catch (t4) {
                if (Ee(n2), t4 !== t4 + 0) throw t4;
                Se(1, 0);
              }
            }, i: function(t3, e3, n2) {
              var r3 = Ae();
              try {
                yt(t3)(e3, n2);
              } catch (t4) {
                if (Ee(r3), t4 !== t4 + 0) throw t4;
                Se(1, 0);
              }
            }, ha: function(t3, e3, n2, r3) {
              var i3 = Ae();
              try {
                yt(t3)(e3, n2, r3);
              } catch (t4) {
                if (Ee(i3), t4 !== t4 + 0) throw t4;
                Se(1, 0);
              }
            }, m: function(t3, e3, n2, r3) {
              var i3 = Ae();
              try {
                yt(t3)(e3, n2, r3);
              } catch (t4) {
                if (Ee(i3), t4 !== t4 + 0) throw t4;
                Se(1, 0);
              }
            }, v: function(t3, e3, n2, r3, i3) {
              var o2 = Ae();
              try {
                yt(t3)(e3, n2, r3, i3);
              } catch (t4) {
                if (Ee(o2), t4 !== t4 + 0) throw t4;
                Se(1, 0);
              }
            }, u: function(t3, e3, n2, r3, i3, o2) {
              var a2 = Ae();
              try {
                yt(t3)(e3, n2, r3, i3, o2);
              } catch (t4) {
                if (Ee(a2), t4 !== t4 + 0) throw t4;
                Se(1, 0);
              }
            }, O: function(t3, e3, n2, r3, i3, o2, a2) {
              var s2 = Ae();
              try {
                yt(t3)(e3, n2, r3, i3, o2, a2);
              } catch (t4) {
                if (Ee(s2), t4 !== t4 + 0) throw t4;
                Se(1, 0);
              }
            }, A: function(t3, e3, n2, r3, i3, o2, a2, s2) {
              var u2 = Ae();
              try {
                yt(t3)(e3, n2, r3, i3, o2, a2, s2);
              } catch (t4) {
                if (Ee(u2), t4 !== t4 + 0) throw t4;
                Se(1, 0);
              }
            }, ka: function(t3, e3, n2, r3, i3, o2, a2, s2, u2) {
              var c2 = Ae();
              try {
                yt(t3)(e3, n2, r3, i3, o2, a2, s2, u2);
              } catch (t4) {
                if (Ee(c2), t4 !== t4 + 0) throw t4;
                Se(1, 0);
              }
            }, C: function(t3, e3, n2, r3, i3, o2, a2, s2, u2, c2, l2) {
              var p2 = Ae();
              try {
                yt(t3)(e3, n2, r3, i3, o2, a2, s2, u2, c2, l2);
              } catch (t4) {
                if (Ee(p2), t4 !== t4 + 0) throw t4;
                Se(1, 0);
              }
            }, D: function(t3, e3, n2, r3, i3, o2, a2, s2, u2, c2, l2, p2, f2, d2, h2, g2) {
              var b2 = Ae();
              try {
                yt(t3)(e3, n2, r3, i3, o2, a2, s2, u2, c2, l2, p2, f2, d2, h2, g2);
              } catch (t4) {
                if (Ee(b2), t4 !== t4 + 0) throw t4;
                Se(1, 0);
              }
            }, fa: function(t3, e3, n2, r3, i3, o2, a2, s2) {
              var u2 = Ae();
              try {
                Fe(t3, e3, n2, r3, i3, o2, a2, s2);
              } catch (t4) {
                if (Ee(u2), t4 !== t4 + 0) throw t4;
                Se(1, 0);
              }
            }, da: function(t3, e3, n2, r3, i3, o2, a2, s2, u2, c2, l2, p2) {
              var f2 = Ae();
              try {
                Le(t3, e3, n2, r3, i3, o2, a2, s2, u2, c2, l2, p2);
              } catch (t4) {
                if (Ee(f2), t4 !== t4 + 0) throw t4;
                Se(1, 0);
              }
            }, ea: function(t3, e3, n2, r3, i3, o2) {
              var a2 = Ae();
              try {
                Ne(t3, e3, n2, r3, i3, o2);
              } catch (t4) {
                if (Ee(a2), t4 !== t4 + 0) throw t4;
                Se(1, 0);
              }
            }, o: function(t3) {
              return t3;
            }, a: $ || s.wasmMemory, G: function(t3) {
              ae = t3;
            }, la: le, z: function(t3, e3, n2, r3) {
              return le(t3, e3, n2, r3);
            } };
            !(function() {
              function t3(t4, e4) {
                s.asm = t4.exports, dt.qc.push(s.asm.sb), q = s.asm.ub, Y.unshift(s.asm.Va), k = e4, x || (et--, s.monitorRunDependencies && s.monitorRunDependencies(et), 0 == et && (rt && (t4 = rt, rt = null, t4())));
              }
              function e3(e4) {
                t3(e4.instance, e4.module);
              }
              function n2(t4) {
                return (function() {
                  if (!E && (_ || v)) {
                    if ("function" == typeof fetch && !tt.startsWith("file://")) return fetch(tt, { credentials: "same-origin" }).then((function(t5) {
                      if (!t5.ok) throw "failed to load wasm binary file at '" + tt + "'";
                      return t5.arrayBuffer();
                    })).catch((function() {
                      return at();
                    }));
                    if (p) return new Promise((function(t5, e4) {
                      p(tt, (function(e5) {
                        t5(new Uint8Array(e5));
                      }), e4);
                    }));
                  }
                  return Promise.resolve().then((function() {
                    return at();
                  }));
                })().then((function(t5) {
                  return WebAssembly.instantiate(t5, r3);
                })).then((function(t5) {
                  return t5;
                })).then(t4, (function(t5) {
                  P("failed to asynchronously prepare wasm: " + t5), it2(t5);
                }));
              }
              var r3 = { a: fe };
              if (x || (et++, s.monitorRunDependencies && s.monitorRunDependencies(et)), s.instantiateWasm) try {
                return s.instantiateWasm(r3, t3);
              } catch (t4) {
                return P("Module.instantiateWasm callback failed with error: " + t4), false;
              }
              (E || "function" != typeof WebAssembly.instantiateStreaming || ot() || tt.startsWith("file://") || w || "function" != typeof fetch ? n2(e3) : fetch(tt, { credentials: "same-origin" }).then((function(t4) {
                return WebAssembly.instantiateStreaming(t4, r3).then(e3, (function(t5) {
                  return P("wasm streaming compile failed: " + t5), P("falling back to ArrayBuffer instantiation"), n2(e3);
                }));
              }))).catch(c);
            })(), s.___wasm_call_ctors = function() {
              return (s.___wasm_call_ctors = s.asm.Va).apply(null, arguments);
            }, s._OrtInit = function() {
              return (s._OrtInit = s.asm.Wa).apply(null, arguments);
            }, s._OrtCreateSessionOptions = function() {
              return (s._OrtCreateSessionOptions = s.asm.Xa).apply(null, arguments);
            }, s._OrtAppendExecutionProvider = function() {
              return (s._OrtAppendExecutionProvider = s.asm.Ya).apply(null, arguments);
            }, s._OrtAddSessionConfigEntry = function() {
              return (s._OrtAddSessionConfigEntry = s.asm.Za).apply(null, arguments);
            }, s._OrtReleaseSessionOptions = function() {
              return (s._OrtReleaseSessionOptions = s.asm._a).apply(null, arguments);
            }, s._OrtCreateSession = function() {
              return (s._OrtCreateSession = s.asm.$a).apply(null, arguments);
            }, s._OrtReleaseSession = function() {
              return (s._OrtReleaseSession = s.asm.ab).apply(null, arguments);
            }, s._OrtGetInputCount = function() {
              return (s._OrtGetInputCount = s.asm.bb).apply(null, arguments);
            }, s._OrtGetOutputCount = function() {
              return (s._OrtGetOutputCount = s.asm.cb).apply(null, arguments);
            }, s._OrtGetInputName = function() {
              return (s._OrtGetInputName = s.asm.db).apply(null, arguments);
            }, s._OrtGetOutputName = function() {
              return (s._OrtGetOutputName = s.asm.eb).apply(null, arguments);
            }, s._OrtFree = function() {
              return (s._OrtFree = s.asm.fb).apply(null, arguments);
            }, s._OrtCreateTensor = function() {
              return (s._OrtCreateTensor = s.asm.gb).apply(null, arguments);
            }, s._OrtGetTensorData = function() {
              return (s._OrtGetTensorData = s.asm.hb).apply(null, arguments);
            }, s._OrtReleaseTensor = function() {
              return (s._OrtReleaseTensor = s.asm.ib).apply(null, arguments);
            }, s._OrtCreateRunOptions = function() {
              return (s._OrtCreateRunOptions = s.asm.jb).apply(null, arguments);
            }, s._OrtAddRunConfigEntry = function() {
              return (s._OrtAddRunConfigEntry = s.asm.kb).apply(null, arguments);
            }, s._OrtReleaseRunOptions = function() {
              return (s._OrtReleaseRunOptions = s.asm.lb).apply(null, arguments);
            }, s._OrtRun = function() {
              return (s._OrtRun = s.asm.mb).apply(null, arguments);
            }, s._OrtEndProfiling = function() {
              return (s._OrtEndProfiling = s.asm.nb).apply(null, arguments);
            };
            var de2 = s._pthread_self = function() {
              return (de2 = s._pthread_self = s.asm.ob).apply(null, arguments);
            }, he2 = s._malloc = function() {
              return (he2 = s._malloc = s.asm.pb).apply(null, arguments);
            }, ge = s._free = function() {
              return (ge = s._free = s.asm.qb).apply(null, arguments);
            }, be2 = s._fflush = function() {
              return (be2 = s._fflush = s.asm.rb).apply(null, arguments);
            };
            s.__emscripten_tls_init = function() {
              return (s.__emscripten_tls_init = s.asm.sb).apply(null, arguments);
            };
            var me = s.___funcs_on_exit = function() {
              return (me = s.___funcs_on_exit = s.asm.tb).apply(null, arguments);
            }, ye = s.__emscripten_thread_init = function() {
              return (ye = s.__emscripten_thread_init = s.asm.vb).apply(null, arguments);
            };
            s.__emscripten_thread_crashed = function() {
              return (s.__emscripten_thread_crashed = s.asm.wb).apply(null, arguments);
            };
            var _e, ve = s._emscripten_run_in_main_runtime_thread_js = function() {
              return (ve = s._emscripten_run_in_main_runtime_thread_js = s.asm.xb).apply(null, arguments);
            }, we = s.__emscripten_proxy_execute_task_queue = function() {
              return (we = s.__emscripten_proxy_execute_task_queue = s.asm.yb).apply(null, arguments);
            }, xe = s.__emscripten_thread_free_data = function() {
              return (xe = s.__emscripten_thread_free_data = s.asm.zb).apply(null, arguments);
            }, Te = s.__emscripten_thread_exit = function() {
              return (Te = s.__emscripten_thread_exit = s.asm.Ab).apply(null, arguments);
            }, Se = s._setThrew = function() {
              return (Se = s._setThrew = s.asm.Bb).apply(null, arguments);
            }, Oe = s._emscripten_stack_set_limits = function() {
              return (Oe = s._emscripten_stack_set_limits = s.asm.Cb).apply(null, arguments);
            }, Ae = s.stackSave = function() {
              return (Ae = s.stackSave = s.asm.Db).apply(null, arguments);
            }, Ee = s.stackRestore = function() {
              return (Ee = s.stackRestore = s.asm.Eb).apply(null, arguments);
            }, Ie = s.stackAlloc = function() {
              return (Ie = s.stackAlloc = s.asm.Fb).apply(null, arguments);
            }, Pe = s.___cxa_can_catch = function() {
              return (Pe = s.___cxa_can_catch = s.asm.Gb).apply(null, arguments);
            }, De = s.___cxa_is_pointer_type = function() {
              return (De = s.___cxa_is_pointer_type = s.asm.Hb).apply(null, arguments);
            }, $e = s.dynCall_j = function() {
              return ($e = s.dynCall_j = s.asm.Ib).apply(null, arguments);
            }, ke = s.dynCall_iiiiij = function() {
              return (ke = s.dynCall_iiiiij = s.asm.Jb).apply(null, arguments);
            }, Ce = s.dynCall_jii = function() {
              return (Ce = s.dynCall_jii = s.asm.Kb).apply(null, arguments);
            }, Fe = s.dynCall_viiiiij = function() {
              return (Fe = s.dynCall_viiiiij = s.asm.Lb).apply(null, arguments);
            }, Ne = s.dynCall_vjji = function() {
              return (Ne = s.dynCall_vjji = s.asm.Mb).apply(null, arguments);
            }, Le = s.dynCall_viiijjjii = function() {
              return (Le = s.dynCall_viiijjjii = s.asm.Nb).apply(null, arguments);
            }, Re = s.dynCall_iij = function() {
              return (Re = s.dynCall_iij = s.asm.Ob).apply(null, arguments);
            }, je = s.dynCall_ji = function() {
              return (je = s.dynCall_ji = s.asm.Pb).apply(null, arguments);
            }, Me = s.dynCall_iiiiiij = function() {
              return (Me = s.dynCall_iiiiiij = s.asm.Qb).apply(null, arguments);
            }, Ue = s.dynCall_iiij = function() {
              return (Ue = s.dynCall_iiij = s.asm.Rb).apply(null, arguments);
            };
            function Ve() {
              function t3() {
                if (!_e && (_e = true, s.calledRun = true, !M) && (x || ht(Y), u(s), s.onRuntimeInitialized && s.onRuntimeInitialized(), !x)) {
                  if (s.postRun) for ("function" == typeof s.postRun && (s.postRun = [s.postRun]); s.postRun.length; ) {
                    var t4 = s.postRun.shift();
                    Z.unshift(t4);
                  }
                  ht(Z);
                }
              }
              if (!(0 < et)) if (x) u(s), x || ht(Y), postMessage({ cmd: "loaded" });
              else {
                if (s.preRun) for ("function" == typeof s.preRun && (s.preRun = [s.preRun]); s.preRun.length; ) Q();
                ht(X), 0 < et || (s.setStatus ? (s.setStatus("Running..."), setTimeout((function() {
                  setTimeout((function() {
                    s.setStatus("");
                  }), 1), t3();
                }), 1)) : t3());
              }
            }
            if (s.UTF8ToString = B, s.stringToUTF8 = function(t3, e3, n2) {
              return z2(t3, r2(), e3, n2);
            }, s.lengthBytesUTF8 = G, s.keepRuntimeAlive = J, s.wasmMemory = $, s.stackSave = Ae, s.stackRestore = Ee, s.stackAlloc = Ie, s.ExitStatus = ut, s.PThread = dt, rt = function t3() {
              _e || Ve(), _e || (rt = t3);
            }, s.preInit) for ("function" == typeof s.preInit && (s.preInit = [s.preInit]); 0 < s.preInit.length; ) s.preInit.pop()();
            return Ve(), t2.ready;
          });
          t.exports = r;
        }, 932: (t, e, n) => {
          var _scriptDir, r = (_scriptDir = (_scriptDir = "undefined" != typeof document && document.currentScript ? document.currentScript.src : void 0) || "/index.js", function(t2) {
            var e2, r2, i2;
            t2 = t2 || {}, e2 || (e2 = void 0 !== t2 ? t2 : {}), e2.ready = new Promise((function(t3, e3) {
              r2 = t3, i2 = e3;
            }));
            var o, a, s, u, c, l, p = Object.assign({}, e2), f = "./this.program", d = (t3, e3) => {
              throw e3;
            }, h = "object" == typeof window, g = "function" == typeof importScripts, b = "object" == typeof process$1 && "object" == typeof process$1.versions && "string" == typeof process$1.versions.node, m = "";
            b ? (m = g ? n(908).dirname(m) + "/" : "//", l = () => {
              c || (u = n(1384), c = n(908));
            }, o = function(t3, e3) {
              return l(), t3 = c.normalize(t3), u.readFileSync(t3, e3 ? void 0 : "utf8");
            }, s = (t3) => ((t3 = o(t3, true)).buffer || (t3 = new Uint8Array(t3)), t3), a = (t3, e3, n2) => {
              l(), t3 = c.normalize(t3), u.readFile(t3, (function(t4, r3) {
                t4 ? n2(t4) : e3(r3.buffer);
              }));
            }, 1 < process$1.argv.length && (f = process$1.argv[1].replace(/\\/g, "/")), process$1.argv.slice(2), process$1.on("uncaughtException", (function(t3) {
              if (!(t3 instanceof K)) throw t3;
            })), process$1.on("unhandledRejection", (function(t3) {
              throw t3;
            })), d = (t3, e3) => {
              if (w || 0 < U) throw process$1.exitCode = t3, e3;
              e3 instanceof K || v("exiting due to exception: " + e3), process$1.exit(t3);
            }, e2.inspect = function() {
              return "[Emscripten Module object]";
            }) : (h || g) && (g ? m = self.location.href : "undefined" != typeof document && document.currentScript && (m = document.currentScript.src), _scriptDir && (m = _scriptDir), m = 0 !== m.indexOf("blob:") ? m.substr(0, m.replace(/[?#].*/, "").lastIndexOf("/") + 1) : "", o = (t3) => {
              var e3 = new XMLHttpRequest();
              return e3.open("GET", t3, false), e3.send(null), e3.responseText;
            }, g && (s = (t3) => {
              var e3 = new XMLHttpRequest();
              return e3.open("GET", t3, false), e3.responseType = "arraybuffer", e3.send(null), new Uint8Array(e3.response);
            }), a = (t3, e3, n2) => {
              var r3 = new XMLHttpRequest();
              r3.open("GET", t3, true), r3.responseType = "arraybuffer", r3.onload = () => {
                200 == r3.status || 0 == r3.status && r3.response ? e3(r3.response) : n2();
              }, r3.onerror = n2, r3.send(null);
            });
            var y, _ = e2.print || console.log.bind(console), v = e2.printErr || console.warn.bind(console);
            Object.assign(e2, p), p = null, e2.thisProgram && (f = e2.thisProgram), e2.quit && (d = e2.quit), e2.wasmBinary && (y = e2.wasmBinary);
            var w = e2.noExitRuntime || false;
            "object" != typeof WebAssembly && W("no native wasm support detected");
            var x, T, S, O, A, E, I = false, P = "undefined" != typeof TextDecoder ? new TextDecoder("utf8") : void 0;
            function D(t3, e3, n2) {
              var r3 = (e3 >>>= 0) + n2;
              for (n2 = e3; t3[n2] && !(n2 >= r3); ) ++n2;
              if (16 < n2 - e3 && t3.buffer && P) return P.decode(t3.subarray(e3, n2));
              for (r3 = ""; e3 < n2; ) {
                var i3 = t3[e3++];
                if (128 & i3) {
                  var o2 = 63 & t3[e3++];
                  if (192 == (224 & i3)) r3 += String.fromCharCode((31 & i3) << 6 | o2);
                  else {
                    var a2 = 63 & t3[e3++];
                    65536 > (i3 = 224 == (240 & i3) ? (15 & i3) << 12 | o2 << 6 | a2 : (7 & i3) << 18 | o2 << 12 | a2 << 6 | 63 & t3[e3++]) ? r3 += String.fromCharCode(i3) : (i3 -= 65536, r3 += String.fromCharCode(55296 | i3 >> 10, 56320 | 1023 & i3));
                  }
                } else r3 += String.fromCharCode(i3);
              }
              return r3;
            }
            function $(t3, e3) {
              return (t3 >>>= 0) ? D(O, t3, e3) : "";
            }
            function k(t3, e3, n2, r3) {
              if (!(0 < r3)) return 0;
              var i3 = n2 >>>= 0;
              r3 = n2 + r3 - 1;
              for (var o2 = 0; o2 < t3.length; ++o2) {
                var a2 = t3.charCodeAt(o2);
                if (55296 <= a2 && 57343 >= a2 && (a2 = 65536 + ((1023 & a2) << 10) | 1023 & t3.charCodeAt(++o2)), 127 >= a2) {
                  if (n2 >= r3) break;
                  e3[n2++ >>> 0] = a2;
                } else {
                  if (2047 >= a2) {
                    if (n2 + 1 >= r3) break;
                    e3[n2++ >>> 0] = 192 | a2 >> 6;
                  } else {
                    if (65535 >= a2) {
                      if (n2 + 2 >= r3) break;
                      e3[n2++ >>> 0] = 224 | a2 >> 12;
                    } else {
                      if (n2 + 3 >= r3) break;
                      e3[n2++ >>> 0] = 240 | a2 >> 18, e3[n2++ >>> 0] = 128 | a2 >> 12 & 63;
                    }
                    e3[n2++ >>> 0] = 128 | a2 >> 6 & 63;
                  }
                  e3[n2++ >>> 0] = 128 | 63 & a2;
                }
              }
              return e3[n2 >>> 0] = 0, n2 - i3;
            }
            function C(t3) {
              for (var e3 = 0, n2 = 0; n2 < t3.length; ++n2) {
                var r3 = t3.charCodeAt(n2);
                127 >= r3 ? e3++ : 2047 >= r3 ? e3 += 2 : 55296 <= r3 && 57343 >= r3 ? (e3 += 4, ++n2) : e3 += 3;
              }
              return e3;
            }
            function F() {
              var t3 = x.buffer;
              T = t3, e2.HEAP8 = S = new Int8Array(t3), e2.HEAP16 = new Int16Array(t3), e2.HEAP32 = A = new Int32Array(t3), e2.HEAPU8 = O = new Uint8Array(t3), e2.HEAPU16 = new Uint16Array(t3), e2.HEAPU32 = E = new Uint32Array(t3), e2.HEAPF32 = new Float32Array(t3), e2.HEAPF64 = new Float64Array(t3);
            }
            var N, L = [], R = [], j = [], M = [], U = 0;
            function V() {
              var t3 = e2.preRun.shift();
              L.unshift(t3);
            }
            var B, z2 = 0, H = null;
            function W(t3) {
              throw e2.onAbort && e2.onAbort(t3), v(t3 = "Aborted(" + t3 + ")"), I = true, t3 = new WebAssembly.RuntimeError(t3 + ". Build with -sASSERTIONS for more info."), i2(t3), t3;
            }
            function q() {
              return B.startsWith("data:application/octet-stream;base64,");
            }
            if (B = "ort-wasm.wasm", !q()) {
              var X = B;
              B = e2.locateFile ? e2.locateFile(X, m) : m + X;
            }
            function Y() {
              var t3 = B;
              try {
                if (t3 == B && y) return new Uint8Array(y);
                if (s) return s(t3);
                throw "both async and sync fetching of the wasm failed";
              } catch (t4) {
                W(t4);
              }
            }
            function K(t3) {
              this.name = "ExitStatus", this.message = "Program terminated with exit(" + t3 + ")", this.status = t3;
            }
            function Z(t3) {
              for (; 0 < t3.length; ) t3.shift()(e2);
            }
            var J = [], Q = 0, tt = 0;
            function et(t3) {
              this.Db = t3, this.zb = t3 - 24, this.Ub = function(t4) {
                E[this.zb + 4 >> 2 >>> 0] = t4;
              }, this.Eb = function() {
                return E[this.zb + 4 >> 2 >>> 0];
              }, this.Sb = function(t4) {
                E[this.zb + 8 >> 2 >>> 0] = t4;
              }, this.Wb = function() {
                return E[this.zb + 8 >> 2 >>> 0];
              }, this.Tb = function() {
                A[this.zb >> 2 >>> 0] = 0;
              }, this.Ib = function(t4) {
                S[this.zb + 12 >> 0 >>> 0] = t4 ? 1 : 0;
              }, this.Pb = function() {
                return 0 != S[this.zb + 12 >> 0 >>> 0];
              }, this.Jb = function(t4) {
                S[this.zb + 13 >> 0 >>> 0] = t4 ? 1 : 0;
              }, this.Lb = function() {
                return 0 != S[this.zb + 13 >> 0 >>> 0];
              }, this.Rb = function(t4, e3) {
                this.Fb(0), this.Ub(t4), this.Sb(e3), this.Tb(), this.Ib(false), this.Jb(false);
              }, this.Nb = function() {
                A[this.zb >> 2 >>> 0] += 1;
              }, this.Xb = function() {
                var t4 = A[this.zb >> 2 >>> 0];
                return A[this.zb >> 2 >>> 0] = t4 - 1, 1 === t4;
              }, this.Fb = function(t4) {
                E[this.zb + 16 >> 2 >>> 0] = t4;
              }, this.Ob = function() {
                return E[this.zb + 16 >> 2 >>> 0];
              }, this.Qb = function() {
                if (Et(this.Eb())) return E[this.Db >> 2 >>> 0];
                var t4 = this.Ob();
                return 0 !== t4 ? t4 : this.Db;
              };
            }
            function nt(t3) {
              return _t(new et(t3).zb);
            }
            var rt = [];
            function it2(t3) {
              var e3 = rt[t3];
              return e3 || (t3 >= rt.length && (rt.length = t3 + 1), rt[t3] = e3 = N.get(t3)), e3;
            }
            function ot(t3) {
              var e3 = C(t3) + 1, n2 = yt(e3);
              return n2 && k(t3, S, n2, e3), n2;
            }
            var at = {};
            function st() {
              if (!ut) {
                var t3, e3 = { USER: "web_user", LOGNAME: "web_user", PATH: "/", PWD: "/", HOME: "/home/web_user", LANG: ("object" == typeof navigator && navigator.languages && navigator.languages[0] || "C").replace("-", "_") + ".UTF-8", _: f || "./this.program" };
                for (t3 in at) void 0 === at[t3] ? delete e3[t3] : e3[t3] = at[t3];
                var n2 = [];
                for (t3 in e3) n2.push(t3 + "=" + e3[t3]);
                ut = n2;
              }
              return ut;
            }
            var ut, ct = [null, [], []];
            function lt2(t3, e3) {
              var n2 = ct[t3];
              0 === e3 || 10 === e3 ? ((1 === t3 ? _ : v)(D(n2, 0)), n2.length = 0) : n2.push(e3);
            }
            var pt2 = 0;
            function ft(t3) {
              return 0 == t3 % 4 && (0 != t3 % 100 || 0 == t3 % 400);
            }
            var dt = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], ht = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
            function gt(t3, e3, n2, r3) {
              function i3(t4, e4, n3) {
                for (t4 = "number" == typeof t4 ? t4.toString() : t4 || ""; t4.length < e4; ) t4 = n3[0] + t4;
                return t4;
              }
              function o2(t4, e4) {
                return i3(t4, e4, "0");
              }
              function a2(t4, e4) {
                function n3(t5) {
                  return 0 > t5 ? -1 : 0 < t5 ? 1 : 0;
                }
                var r4;
                return 0 === (r4 = n3(t4.getFullYear() - e4.getFullYear())) && 0 === (r4 = n3(t4.getMonth() - e4.getMonth())) && (r4 = n3(t4.getDate() - e4.getDate())), r4;
              }
              function s2(t4) {
                switch (t4.getDay()) {
                  case 0:
                    return new Date(t4.getFullYear() - 1, 11, 29);
                  case 1:
                    return t4;
                  case 2:
                    return new Date(t4.getFullYear(), 0, 3);
                  case 3:
                    return new Date(t4.getFullYear(), 0, 2);
                  case 4:
                    return new Date(t4.getFullYear(), 0, 1);
                  case 5:
                    return new Date(t4.getFullYear() - 1, 11, 31);
                  case 6:
                    return new Date(t4.getFullYear() - 1, 11, 30);
                }
              }
              function u2(t4) {
                var e4 = t4.Bb;
                for (t4 = new Date(new Date(t4.Cb + 1900, 0, 1).getTime()); 0 < e4; ) {
                  var n3 = t4.getMonth(), r4 = (ft(t4.getFullYear()) ? dt : ht)[n3];
                  if (!(e4 > r4 - t4.getDate())) {
                    t4.setDate(t4.getDate() + e4);
                    break;
                  }
                  e4 -= r4 - t4.getDate() + 1, t4.setDate(1), 11 > n3 ? t4.setMonth(n3 + 1) : (t4.setMonth(0), t4.setFullYear(t4.getFullYear() + 1));
                }
                return n3 = new Date(t4.getFullYear() + 1, 0, 4), e4 = s2(new Date(t4.getFullYear(), 0, 4)), n3 = s2(n3), 0 >= a2(e4, t4) ? 0 >= a2(n3, t4) ? t4.getFullYear() + 1 : t4.getFullYear() : t4.getFullYear() - 1;
              }
              var c2 = A[r3 + 40 >> 2 >>> 0];
              for (var l2 in r3 = { $b: A[r3 >> 2 >>> 0], Zb: A[r3 + 4 >> 2 >>> 0], Gb: A[r3 + 8 >> 2 >>> 0], Kb: A[r3 + 12 >> 2 >>> 0], Hb: A[r3 + 16 >> 2 >>> 0], Cb: A[r3 + 20 >> 2 >>> 0], Ab: A[r3 + 24 >> 2 >>> 0], Bb: A[r3 + 28 >> 2 >>> 0], bc: A[r3 + 32 >> 2 >>> 0], Yb: A[r3 + 36 >> 2 >>> 0], ac: c2 ? $(c2) : "" }, n2 = $(n2), c2 = { "%c": "%a %b %d %H:%M:%S %Y", "%D": "%m/%d/%y", "%F": "%Y-%m-%d", "%h": "%b", "%r": "%I:%M:%S %p", "%R": "%H:%M", "%T": "%H:%M:%S", "%x": "%m/%d/%y", "%X": "%H:%M:%S", "%Ec": "%c", "%EC": "%C", "%Ex": "%m/%d/%y", "%EX": "%H:%M:%S", "%Ey": "%y", "%EY": "%Y", "%Od": "%d", "%Oe": "%e", "%OH": "%H", "%OI": "%I", "%Om": "%m", "%OM": "%M", "%OS": "%S", "%Ou": "%u", "%OU": "%U", "%OV": "%V", "%Ow": "%w", "%OW": "%W", "%Oy": "%y" }) n2 = n2.replace(new RegExp(l2, "g"), c2[l2]);
              var p2 = "Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "), f2 = "January February March April May June July August September October November December".split(" ");
              for (l2 in c2 = { "%a": function(t4) {
                return p2[t4.Ab].substring(0, 3);
              }, "%A": function(t4) {
                return p2[t4.Ab];
              }, "%b": function(t4) {
                return f2[t4.Hb].substring(0, 3);
              }, "%B": function(t4) {
                return f2[t4.Hb];
              }, "%C": function(t4) {
                return o2((t4.Cb + 1900) / 100 | 0, 2);
              }, "%d": function(t4) {
                return o2(t4.Kb, 2);
              }, "%e": function(t4) {
                return i3(t4.Kb, 2, " ");
              }, "%g": function(t4) {
                return u2(t4).toString().substring(2);
              }, "%G": function(t4) {
                return u2(t4);
              }, "%H": function(t4) {
                return o2(t4.Gb, 2);
              }, "%I": function(t4) {
                return 0 == (t4 = t4.Gb) ? t4 = 12 : 12 < t4 && (t4 -= 12), o2(t4, 2);
              }, "%j": function(t4) {
                for (var e4 = 0, n3 = 0; n3 <= t4.Hb - 1; e4 += (ft(t4.Cb + 1900) ? dt : ht)[n3++]) ;
                return o2(t4.Kb + e4, 3);
              }, "%m": function(t4) {
                return o2(t4.Hb + 1, 2);
              }, "%M": function(t4) {
                return o2(t4.Zb, 2);
              }, "%n": function() {
                return "\n";
              }, "%p": function(t4) {
                return 0 <= t4.Gb && 12 > t4.Gb ? "AM" : "PM";
              }, "%S": function(t4) {
                return o2(t4.$b, 2);
              }, "%t": function() {
                return "	";
              }, "%u": function(t4) {
                return t4.Ab || 7;
              }, "%U": function(t4) {
                return o2(Math.floor((t4.Bb + 7 - t4.Ab) / 7), 2);
              }, "%V": function(t4) {
                var e4 = Math.floor((t4.Bb + 7 - (t4.Ab + 6) % 7) / 7);
                if (2 >= (t4.Ab + 371 - t4.Bb - 2) % 7 && e4++, e4) 53 == e4 && (4 == (n3 = (t4.Ab + 371 - t4.Bb) % 7) || 3 == n3 && ft(t4.Cb) || (e4 = 1));
                else {
                  e4 = 52;
                  var n3 = (t4.Ab + 7 - t4.Bb - 1) % 7;
                  (4 == n3 || 5 == n3 && ft(t4.Cb % 400 - 1)) && e4++;
                }
                return o2(e4, 2);
              }, "%w": function(t4) {
                return t4.Ab;
              }, "%W": function(t4) {
                return o2(Math.floor((t4.Bb + 7 - (t4.Ab + 6) % 7) / 7), 2);
              }, "%y": function(t4) {
                return (t4.Cb + 1900).toString().substring(2);
              }, "%Y": function(t4) {
                return t4.Cb + 1900;
              }, "%z": function(t4) {
                var e4 = 0 <= (t4 = t4.Yb);
                return t4 = Math.abs(t4) / 60, (e4 ? "+" : "-") + String("0000" + (t4 / 60 * 100 + t4 % 60)).slice(-4);
              }, "%Z": function(t4) {
                return t4.ac;
              }, "%%": function() {
                return "%";
              } }, n2 = n2.replace(/%%/g, "\0\0"), c2) n2.includes(l2) && (n2 = n2.replace(new RegExp(l2, "g"), c2[l2](r3)));
              return l2 = (function(t4) {
                var e4 = Array(C(t4) + 1);
                return k(t4, e4, 0, e4.length), e4;
              })(n2 = n2.replace(/\0\0/g, "%")), l2.length > e3 ? 0 : (S.set(l2, t3 >>> 0), l2.length - 1);
            }
            var bt = { a: function(t3) {
              return yt(t3 + 24) + 24;
            }, m: function(t3) {
              return (t3 = new et(t3)).Pb() || (t3.Ib(true), Q--), t3.Jb(false), J.push(t3), t3.Nb(), t3.Qb();
            }, ia: function(t3) {
              throw v("Unexpected exception thrown, this is not properly supported - aborting"), I = true, t3;
            }, w: function() {
              xt(0);
              var t3 = J.pop();
              if (t3.Xb() && !t3.Lb()) {
                var e3 = t3.Wb();
                e3 && it2(e3)(t3.Db), nt(t3.Db);
              }
              tt = 0;
            }, d: function() {
              var t3 = tt;
              if (!t3) return pt2 = 0;
              var e3 = new et(t3);
              e3.Fb(t3);
              var n2 = e3.Eb();
              if (!n2) return pt2 = 0, t3;
              for (var r3 = Array.prototype.slice.call(arguments), i3 = 0; i3 < r3.length; i3++) {
                var o2 = r3[i3];
                if (0 === o2 || o2 === n2) break;
                if (At(o2, n2, e3.zb + 16)) return pt2 = o2, t3;
              }
              return pt2 = n2, t3;
            }, k: function() {
              var t3 = tt;
              if (!t3) return pt2 = 0;
              var e3 = new et(t3);
              e3.Fb(t3);
              var n2 = e3.Eb();
              if (!n2) return pt2 = 0, t3;
              for (var r3 = Array.prototype.slice.call(arguments), i3 = 0; i3 < r3.length; i3++) {
                var o2 = r3[i3];
                if (0 === o2 || o2 === n2) break;
                if (At(o2, n2, e3.zb + 16)) return pt2 = o2, t3;
              }
              return pt2 = n2, t3;
            }, g: function() {
              var t3 = tt;
              if (!t3) return pt2 = 0;
              var e3 = new et(t3);
              e3.Fb(t3);
              var n2 = e3.Eb();
              if (!n2) return pt2 = 0, t3;
              for (var r3 = Array.prototype.slice.call(arguments), i3 = 0; i3 < r3.length; i3++) {
                var o2 = r3[i3];
                if (0 === o2 || o2 === n2) break;
                if (At(o2, n2, e3.zb + 16)) return pt2 = o2, t3;
              }
              return pt2 = n2, t3;
            }, s: nt, L: function() {
              var t3 = J.pop();
              t3 || W("no exception to throw");
              var e3 = t3.Db;
              throw t3.Lb() || (J.push(t3), t3.Jb(true), t3.Ib(false), Q++), tt = e3, e3;
            }, b: function(t3, e3, n2) {
              throw new et(t3).Rb(e3, n2), tt = t3, Q++, t3;
            }, la: function() {
              return Q;
            }, i: function(t3) {
              throw tt || (tt = t3), t3;
            }, H: function() {
              return 0;
            }, Ba: function() {
            }, pa: function() {
            }, ra: function() {
            }, ka: function() {
              return 0;
            }, za: function() {
            }, ua: function() {
            }, ya: function() {
            }, R: function() {
            }, qa: function() {
            }, na: function() {
            }, Aa: function() {
            }, oa: function() {
            }, Ha: function() {
            }, Ja: function() {
              W("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking");
            }, Ia: function() {
              W("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking");
            }, S: function() {
              return Date.now();
            }, Ca: function() {
              return true;
            }, Da: function(t3, e3) {
              t3 = new Date(1e3 * (E[t3 >>> 2] + 4294967296 * A[t3 + 4 >>> 2])), A[e3 >> 2 >>> 0] = t3.getUTCSeconds(), A[e3 + 4 >> 2 >>> 0] = t3.getUTCMinutes(), A[e3 + 8 >> 2 >>> 0] = t3.getUTCHours(), A[e3 + 12 >> 2 >>> 0] = t3.getUTCDate(), A[e3 + 16 >> 2 >>> 0] = t3.getUTCMonth(), A[e3 + 20 >> 2 >>> 0] = t3.getUTCFullYear() - 1900, A[e3 + 24 >> 2 >>> 0] = t3.getUTCDay(), A[e3 + 28 >> 2 >>> 0] = (t3.getTime() - Date.UTC(t3.getUTCFullYear(), 0, 1, 0, 0, 0, 0)) / 864e5 | 0;
            }, Ea: function(t3, e3) {
              t3 = new Date(1e3 * (E[t3 >>> 2] + 4294967296 * A[t3 + 4 >>> 2])), A[e3 >> 2 >>> 0] = t3.getSeconds(), A[e3 + 4 >> 2 >>> 0] = t3.getMinutes(), A[e3 + 8 >> 2 >>> 0] = t3.getHours(), A[e3 + 12 >> 2 >>> 0] = t3.getDate(), A[e3 + 16 >> 2 >>> 0] = t3.getMonth(), A[e3 + 20 >> 2 >>> 0] = t3.getFullYear() - 1900, A[e3 + 24 >> 2 >>> 0] = t3.getDay();
              var n2 = new Date(t3.getFullYear(), 0, 1);
              A[e3 + 28 >> 2 >>> 0] = (t3.getTime() - n2.getTime()) / 864e5 | 0, A[e3 + 36 >> 2 >>> 0] = -60 * t3.getTimezoneOffset();
              var r3 = new Date(t3.getFullYear(), 6, 1).getTimezoneOffset();
              n2 = n2.getTimezoneOffset(), A[e3 + 32 >> 2 >>> 0] = 0 | (r3 != n2 && t3.getTimezoneOffset() == Math.min(n2, r3));
            }, Fa: function(t3) {
              var e3 = new Date(A[t3 + 20 >> 2 >>> 0] + 1900, A[t3 + 16 >> 2 >>> 0], A[t3 + 12 >> 2 >>> 0], A[t3 + 8 >> 2 >>> 0], A[t3 + 4 >> 2 >>> 0], A[t3 >> 2 >>> 0], 0), n2 = A[t3 + 32 >> 2 >>> 0], r3 = e3.getTimezoneOffset(), i3 = new Date(e3.getFullYear(), 0, 1), o2 = new Date(e3.getFullYear(), 6, 1).getTimezoneOffset(), a2 = i3.getTimezoneOffset(), s2 = Math.min(a2, o2);
              return 0 > n2 ? A[t3 + 32 >> 2 >>> 0] = Number(o2 != a2 && s2 == r3) : 0 < n2 != (s2 == r3) && (o2 = Math.max(a2, o2), e3.setTime(e3.getTime() + 6e4 * ((0 < n2 ? s2 : o2) - r3))), A[t3 + 24 >> 2 >>> 0] = e3.getDay(), A[t3 + 28 >> 2 >>> 0] = (e3.getTime() - i3.getTime()) / 864e5 | 0, A[t3 >> 2 >>> 0] = e3.getSeconds(), A[t3 + 4 >> 2 >>> 0] = e3.getMinutes(), A[t3 + 8 >> 2 >>> 0] = e3.getHours(), A[t3 + 12 >> 2 >>> 0] = e3.getDate(), A[t3 + 16 >> 2 >>> 0] = e3.getMonth(), e3.getTime() / 1e3 | 0;
            }, sa: function() {
              return -52;
            }, ta: function() {
            }, Ga: function t3(e3, n2, r3) {
              t3.Vb || (t3.Vb = true, (function(t4, e4, n3) {
                function r4(t5) {
                  return (t5 = t5.toTimeString().match(/\(([A-Za-z ]+)\)$/)) ? t5[1] : "GMT";
                }
                var i3 = (/* @__PURE__ */ new Date()).getFullYear(), o2 = new Date(i3, 0, 1), a2 = new Date(i3, 6, 1);
                i3 = o2.getTimezoneOffset();
                var s2 = a2.getTimezoneOffset();
                A[t4 >> 2 >>> 0] = 60 * Math.max(i3, s2), A[e4 >> 2 >>> 0] = Number(i3 != s2), t4 = r4(o2), e4 = r4(a2), t4 = ot(t4), e4 = ot(e4), s2 < i3 ? (E[n3 >> 2 >>> 0] = t4, E[n3 + 4 >> 2 >>> 0] = e4) : (E[n3 >> 2 >>> 0] = e4, E[n3 + 4 >> 2 >>> 0] = t4);
              })(e3, n2, r3));
            }, B: function() {
              W("");
            }, ma: function() {
              return 4294901760;
            }, I: b ? () => {
              var t3 = process$1.hrtime();
              return 1e3 * t3[0] + t3[1] / 1e6;
            } : () => performance.now(), xa: function(t3, e3, n2) {
              O.copyWithin(t3 >>> 0, e3 >>> 0, e3 + n2 >>> 0);
            }, G: function(t3) {
              var e3 = O.length;
              if (4294901760 < (t3 >>>= 0)) return false;
              for (var n2 = 1; 4 >= n2; n2 *= 2) {
                var r3 = e3 * (1 + 0.2 / n2);
                r3 = Math.min(r3, t3 + 100663296);
                var i3 = Math;
                r3 = Math.max(t3, r3), i3 = i3.min.call(i3, 4294901760, r3 + (65536 - r3 % 65536) % 65536);
                t: {
                  try {
                    x.grow(i3 - T.byteLength + 65535 >>> 16), F();
                    var o2 = 1;
                    break t;
                  } catch (t4) {
                  }
                  o2 = void 0;
                }
                if (o2) return true;
              }
              return false;
            }, va: function(t3, e3) {
              var n2 = 0;
              return st().forEach((function(r3, i3) {
                var o2 = e3 + n2;
                for (i3 = E[t3 + 4 * i3 >> 2 >>> 0] = o2, o2 = 0; o2 < r3.length; ++o2) S[i3++ >> 0 >>> 0] = r3.charCodeAt(o2);
                S[i3 >> 0 >>> 0] = 0, n2 += r3.length + 1;
              })), 0;
            }, wa: function(t3, e3) {
              var n2 = st();
              E[t3 >> 2 >>> 0] = n2.length;
              var r3 = 0;
              return n2.forEach((function(t4) {
                r3 += t4.length + 1;
              })), E[e3 >> 2 >>> 0] = r3, 0;
            }, ba: function(t3) {
              w || 0 < U || (wt(), Z(j), vt(0), ct[1].length && lt2(1, 10), ct[2].length && lt2(2, 10)), w || 0 < U || (e2.onExit && e2.onExit(t3), I = true), d(t3, new K(t3));
            }, E: function() {
              return 52;
            }, Q: function() {
              return 52;
            }, ca: function() {
              return 70;
            }, P: function(t3, e3, n2, r3) {
              for (var i3 = 0, o2 = 0; o2 < n2; o2++) {
                var a2 = E[e3 >> 2 >>> 0], s2 = E[e3 + 4 >> 2 >>> 0];
                e3 += 8;
                for (var u2 = 0; u2 < s2; u2++) lt2(t3, O[a2 + u2 >>> 0]);
                i3 += s2;
              }
              return E[r3 >> 2 >>> 0] = i3, 0;
            }, c: function() {
              return pt2;
            }, ja: function t3(e3, r3) {
              t3.Mb || (t3.Mb = (function() {
                if ("object" == typeof crypto && "function" == typeof crypto.getRandomValues) {
                  var t4 = new Uint8Array(1);
                  return () => (crypto.getRandomValues(t4), t4[0]);
                }
                if (b) try {
                  var e4 = n(Object((function() {
                    var t5 = new Error("Cannot find module 'crypto'");
                    throw t5.code = "MODULE_NOT_FOUND", t5;
                  })()));
                  return () => e4.randomBytes(1)[0];
                } catch (t5) {
                }
                return () => W("randomDevice");
              })());
              for (var i3 = 0; i3 < r3; i3++) S[e3 + i3 >> 0 >>> 0] = t3.Mb();
              return 0;
            }, ea: function(t3, e3, n2) {
              var r3 = Tt();
              try {
                return it2(t3)(e3, n2);
              } catch (t4) {
                if (St(r3), t4 !== t4 + 0) throw t4;
                xt(1, 0);
              }
            }, fa: function(t3, e3, n2) {
              var r3 = Tt();
              try {
                return it2(t3)(e3, n2);
              } catch (t4) {
                if (St(r3), t4 !== t4 + 0) throw t4;
                xt(1, 0);
              }
            }, J: function(t3) {
              var e3 = Tt();
              try {
                return it2(t3)();
              } catch (t4) {
                if (St(e3), t4 !== t4 + 0) throw t4;
                xt(1, 0);
              }
            }, e: function(t3, e3) {
              var n2 = Tt();
              try {
                return it2(t3)(e3);
              } catch (t4) {
                if (St(n2), t4 !== t4 + 0) throw t4;
                xt(1, 0);
              }
            }, N: function(t3, e3, n2) {
              var r3 = Tt();
              try {
                return it2(t3)(e3, n2);
              } catch (t4) {
                if (St(r3), t4 !== t4 + 0) throw t4;
                xt(1, 0);
              }
            }, O: function(t3, e3, n2) {
              var r3 = Tt();
              try {
                return it2(t3)(e3, n2);
              } catch (t4) {
                if (St(r3), t4 !== t4 + 0) throw t4;
                xt(1, 0);
              }
            }, j: function(t3, e3, n2) {
              var r3 = Tt();
              try {
                return it2(t3)(e3, n2);
              } catch (t4) {
                if (St(r3), t4 !== t4 + 0) throw t4;
                xt(1, 0);
              }
            }, o: function(t3, e3, n2, r3) {
              var i3 = Tt();
              try {
                return it2(t3)(e3, n2, r3);
              } catch (t4) {
                if (St(i3), t4 !== t4 + 0) throw t4;
                xt(1, 0);
              }
            }, p: function(t3, e3, n2, r3, i3) {
              var o2 = Tt();
              try {
                return it2(t3)(e3, n2, r3, i3);
              } catch (t4) {
                if (St(o2), t4 !== t4 + 0) throw t4;
                xt(1, 0);
              }
            }, M: function(t3, e3, n2, r3, i3, o2) {
              var a2 = Tt();
              try {
                return it2(t3)(e3, n2, r3, i3, o2);
              } catch (t4) {
                if (St(a2), t4 !== t4 + 0) throw t4;
                xt(1, 0);
              }
            }, r: function(t3, e3, n2, r3, i3, o2) {
              var a2 = Tt();
              try {
                return it2(t3)(e3, n2, r3, i3, o2);
              } catch (t4) {
                if (St(a2), t4 !== t4 + 0) throw t4;
                xt(1, 0);
              }
            }, v: function(t3, e3, n2, r3, i3, o2, a2) {
              var s2 = Tt();
              try {
                return it2(t3)(e3, n2, r3, i3, o2, a2);
              } catch (t4) {
                if (St(s2), t4 !== t4 + 0) throw t4;
                xt(1, 0);
              }
            }, K: function(t3, e3, n2, r3, i3, o2, a2, s2) {
              var u2 = Tt();
              try {
                return it2(t3)(e3, n2, r3, i3, o2, a2, s2);
              } catch (t4) {
                if (St(u2), t4 !== t4 + 0) throw t4;
                xt(1, 0);
              }
            }, D: function(t3, e3, n2, r3, i3, o2, a2, s2, u2, c2, l2, p2) {
              var f2 = Tt();
              try {
                return it2(t3)(e3, n2, r3, i3, o2, a2, s2, u2, c2, l2, p2);
              } catch (t4) {
                if (St(f2), t4 !== t4 + 0) throw t4;
                xt(1, 0);
              }
            }, X: function(t3, e3, n2, r3, i3, o2, a2, s2) {
              var u2 = Tt();
              try {
                return Lt(t3, e3, n2, r3, i3, o2, a2, s2);
              } catch (t4) {
                if (St(u2), t4 !== t4 + 0) throw t4;
                xt(1, 0);
              }
            }, V: function(t3, e3, n2, r3, i3, o2, a2) {
              var s2 = Tt();
              try {
                return Pt(t3, e3, n2, r3, i3, o2, a2);
              } catch (t4) {
                if (St(s2), t4 !== t4 + 0) throw t4;
                xt(1, 0);
              }
            }, U: function(t3, e3, n2, r3, i3) {
              var o2 = Tt();
              try {
                return Rt(t3, e3, n2, r3, i3);
              } catch (t4) {
                if (St(o2), t4 !== t4 + 0) throw t4;
                xt(1, 0);
              }
            }, Z: function(t3, e3, n2, r3) {
              var i3 = Tt();
              try {
                return Ft(t3, e3, n2, r3);
              } catch (t4) {
                if (St(i3), t4 !== t4 + 0) throw t4;
                xt(1, 0);
              }
            }, W: function(t3) {
              var e3 = Tt();
              try {
                return It(t3);
              } catch (t4) {
                if (St(e3), t4 !== t4 + 0) throw t4;
                xt(1, 0);
              }
            }, Y: function(t3, e3) {
              var n2 = Tt();
              try {
                return Nt(t3, e3);
              } catch (t4) {
                if (St(n2), t4 !== t4 + 0) throw t4;
                xt(1, 0);
              }
            }, T: function(t3, e3, n2) {
              var r3 = Tt();
              try {
                return Dt(t3, e3, n2);
              } catch (t4) {
                if (St(r3), t4 !== t4 + 0) throw t4;
                xt(1, 0);
              }
            }, f: function(t3) {
              var e3 = Tt();
              try {
                it2(t3)();
              } catch (t4) {
                if (St(e3), t4 !== t4 + 0) throw t4;
                xt(1, 0);
              }
            }, q: function(t3, e3) {
              var n2 = Tt();
              try {
                it2(t3)(e3);
              } catch (t4) {
                if (St(n2), t4 !== t4 + 0) throw t4;
                xt(1, 0);
              }
            }, h: function(t3, e3, n2) {
              var r3 = Tt();
              try {
                it2(t3)(e3, n2);
              } catch (t4) {
                if (St(r3), t4 !== t4 + 0) throw t4;
                xt(1, 0);
              }
            }, da: function(t3, e3, n2, r3) {
              var i3 = Tt();
              try {
                it2(t3)(e3, n2, r3);
              } catch (t4) {
                if (St(i3), t4 !== t4 + 0) throw t4;
                xt(1, 0);
              }
            }, l: function(t3, e3, n2, r3) {
              var i3 = Tt();
              try {
                it2(t3)(e3, n2, r3);
              } catch (t4) {
                if (St(i3), t4 !== t4 + 0) throw t4;
                xt(1, 0);
              }
            }, t: function(t3, e3, n2, r3, i3) {
              var o2 = Tt();
              try {
                it2(t3)(e3, n2, r3, i3);
              } catch (t4) {
                if (St(o2), t4 !== t4 + 0) throw t4;
                xt(1, 0);
              }
            }, u: function(t3, e3, n2, r3, i3, o2) {
              var a2 = Tt();
              try {
                it2(t3)(e3, n2, r3, i3, o2);
              } catch (t4) {
                if (St(a2), t4 !== t4 + 0) throw t4;
                xt(1, 0);
              }
            }, x: function(t3, e3, n2, r3, i3, o2, a2) {
              var s2 = Tt();
              try {
                it2(t3)(e3, n2, r3, i3, o2, a2);
              } catch (t4) {
                if (St(s2), t4 !== t4 + 0) throw t4;
                xt(1, 0);
              }
            }, z: function(t3, e3, n2, r3, i3, o2, a2, s2) {
              var u2 = Tt();
              try {
                it2(t3)(e3, n2, r3, i3, o2, a2, s2);
              } catch (t4) {
                if (St(u2), t4 !== t4 + 0) throw t4;
                xt(1, 0);
              }
            }, ga: function(t3, e3, n2, r3, i3, o2, a2, s2, u2) {
              var c2 = Tt();
              try {
                it2(t3)(e3, n2, r3, i3, o2, a2, s2, u2);
              } catch (t4) {
                if (St(c2), t4 !== t4 + 0) throw t4;
                xt(1, 0);
              }
            }, A: function(t3, e3, n2, r3, i3, o2, a2, s2, u2, c2, l2) {
              var p2 = Tt();
              try {
                it2(t3)(e3, n2, r3, i3, o2, a2, s2, u2, c2, l2);
              } catch (t4) {
                if (St(p2), t4 !== t4 + 0) throw t4;
                xt(1, 0);
              }
            }, C: function(t3, e3, n2, r3, i3, o2, a2, s2, u2, c2, l2, p2, f2, d2, h2, g2) {
              var b2 = Tt();
              try {
                it2(t3)(e3, n2, r3, i3, o2, a2, s2, u2, c2, l2, p2, f2, d2, h2, g2);
              } catch (t4) {
                if (St(b2), t4 !== t4 + 0) throw t4;
                xt(1, 0);
              }
            }, aa: function(t3, e3, n2, r3, i3, o2, a2, s2) {
              var u2 = Tt();
              try {
                $t(t3, e3, n2, r3, i3, o2, a2, s2);
              } catch (t4) {
                if (St(u2), t4 !== t4 + 0) throw t4;
                xt(1, 0);
              }
            }, _: function(t3, e3, n2, r3, i3, o2, a2, s2, u2, c2, l2, p2) {
              var f2 = Tt();
              try {
                Ct(t3, e3, n2, r3, i3, o2, a2, s2, u2, c2, l2, p2);
              } catch (t4) {
                if (St(f2), t4 !== t4 + 0) throw t4;
                xt(1, 0);
              }
            }, $: function(t3, e3, n2, r3, i3, o2) {
              var a2 = Tt();
              try {
                kt(t3, e3, n2, r3, i3, o2);
              } catch (t4) {
                if (St(a2), t4 !== t4 + 0) throw t4;
                xt(1, 0);
              }
            }, n: function(t3) {
              return t3;
            }, F: function(t3) {
              pt2 = t3;
            }, ha: gt, y: function(t3, e3, n2, r3) {
              return gt(t3, e3, n2, r3);
            } };
            !(function() {
              function t3(t4) {
                e2.asm = t4.exports, x = e2.asm.Ka, F(), N = e2.asm.ib, R.unshift(e2.asm.La), z2--, e2.monitorRunDependencies && e2.monitorRunDependencies(z2), 0 == z2 && (H && (t4 = H, H = null, t4()));
              }
              function n2(e3) {
                t3(e3.instance);
              }
              function r3(t4) {
                return (function() {
                  if (!y && (h || g)) {
                    if ("function" == typeof fetch && !B.startsWith("file://")) return fetch(B, { credentials: "same-origin" }).then((function(t5) {
                      if (!t5.ok) throw "failed to load wasm binary file at '" + B + "'";
                      return t5.arrayBuffer();
                    })).catch((function() {
                      return Y();
                    }));
                    if (a) return new Promise((function(t5, e3) {
                      a(B, (function(e4) {
                        t5(new Uint8Array(e4));
                      }), e3);
                    }));
                  }
                  return Promise.resolve().then((function() {
                    return Y();
                  }));
                })().then((function(t5) {
                  return WebAssembly.instantiate(t5, o2);
                })).then((function(t5) {
                  return t5;
                })).then(t4, (function(t5) {
                  v("failed to asynchronously prepare wasm: " + t5), W(t5);
                }));
              }
              var o2 = { a: bt };
              if (z2++, e2.monitorRunDependencies && e2.monitorRunDependencies(z2), e2.instantiateWasm) try {
                return e2.instantiateWasm(o2, t3);
              } catch (t4) {
                return v("Module.instantiateWasm callback failed with error: " + t4), false;
              }
              (y || "function" != typeof WebAssembly.instantiateStreaming || q() || B.startsWith("file://") || b || "function" != typeof fetch ? r3(n2) : fetch(B, { credentials: "same-origin" }).then((function(t4) {
                return WebAssembly.instantiateStreaming(t4, o2).then(n2, (function(t5) {
                  return v("wasm streaming compile failed: " + t5), v("falling back to ArrayBuffer instantiation"), r3(n2);
                }));
              }))).catch(i2);
            })(), e2.___wasm_call_ctors = function() {
              return (e2.___wasm_call_ctors = e2.asm.La).apply(null, arguments);
            }, e2._OrtInit = function() {
              return (e2._OrtInit = e2.asm.Ma).apply(null, arguments);
            }, e2._OrtCreateSessionOptions = function() {
              return (e2._OrtCreateSessionOptions = e2.asm.Na).apply(null, arguments);
            }, e2._OrtAppendExecutionProvider = function() {
              return (e2._OrtAppendExecutionProvider = e2.asm.Oa).apply(null, arguments);
            }, e2._OrtAddSessionConfigEntry = function() {
              return (e2._OrtAddSessionConfigEntry = e2.asm.Pa).apply(null, arguments);
            }, e2._OrtReleaseSessionOptions = function() {
              return (e2._OrtReleaseSessionOptions = e2.asm.Qa).apply(null, arguments);
            }, e2._OrtCreateSession = function() {
              return (e2._OrtCreateSession = e2.asm.Ra).apply(null, arguments);
            }, e2._OrtReleaseSession = function() {
              return (e2._OrtReleaseSession = e2.asm.Sa).apply(null, arguments);
            }, e2._OrtGetInputCount = function() {
              return (e2._OrtGetInputCount = e2.asm.Ta).apply(null, arguments);
            }, e2._OrtGetOutputCount = function() {
              return (e2._OrtGetOutputCount = e2.asm.Ua).apply(null, arguments);
            }, e2._OrtGetInputName = function() {
              return (e2._OrtGetInputName = e2.asm.Va).apply(null, arguments);
            }, e2._OrtGetOutputName = function() {
              return (e2._OrtGetOutputName = e2.asm.Wa).apply(null, arguments);
            }, e2._OrtFree = function() {
              return (e2._OrtFree = e2.asm.Xa).apply(null, arguments);
            }, e2._OrtCreateTensor = function() {
              return (e2._OrtCreateTensor = e2.asm.Ya).apply(null, arguments);
            }, e2._OrtGetTensorData = function() {
              return (e2._OrtGetTensorData = e2.asm.Za).apply(null, arguments);
            }, e2._OrtReleaseTensor = function() {
              return (e2._OrtReleaseTensor = e2.asm._a).apply(null, arguments);
            }, e2._OrtCreateRunOptions = function() {
              return (e2._OrtCreateRunOptions = e2.asm.$a).apply(null, arguments);
            }, e2._OrtAddRunConfigEntry = function() {
              return (e2._OrtAddRunConfigEntry = e2.asm.ab).apply(null, arguments);
            }, e2._OrtReleaseRunOptions = function() {
              return (e2._OrtReleaseRunOptions = e2.asm.bb).apply(null, arguments);
            }, e2._OrtRun = function() {
              return (e2._OrtRun = e2.asm.cb).apply(null, arguments);
            }, e2._OrtEndProfiling = function() {
              return (e2._OrtEndProfiling = e2.asm.db).apply(null, arguments);
            };
            var mt, yt = e2._malloc = function() {
              return (yt = e2._malloc = e2.asm.eb).apply(null, arguments);
            }, _t = e2._free = function() {
              return (_t = e2._free = e2.asm.fb).apply(null, arguments);
            }, vt = e2._fflush = function() {
              return (vt = e2._fflush = e2.asm.gb).apply(null, arguments);
            }, wt = e2.___funcs_on_exit = function() {
              return (wt = e2.___funcs_on_exit = e2.asm.hb).apply(null, arguments);
            }, xt = e2._setThrew = function() {
              return (xt = e2._setThrew = e2.asm.jb).apply(null, arguments);
            }, Tt = e2.stackSave = function() {
              return (Tt = e2.stackSave = e2.asm.kb).apply(null, arguments);
            }, St = e2.stackRestore = function() {
              return (St = e2.stackRestore = e2.asm.lb).apply(null, arguments);
            }, Ot = e2.stackAlloc = function() {
              return (Ot = e2.stackAlloc = e2.asm.mb).apply(null, arguments);
            }, At = e2.___cxa_can_catch = function() {
              return (At = e2.___cxa_can_catch = e2.asm.nb).apply(null, arguments);
            }, Et = e2.___cxa_is_pointer_type = function() {
              return (Et = e2.___cxa_is_pointer_type = e2.asm.ob).apply(null, arguments);
            }, It = e2.dynCall_j = function() {
              return (It = e2.dynCall_j = e2.asm.pb).apply(null, arguments);
            }, Pt = e2.dynCall_iiiiij = function() {
              return (Pt = e2.dynCall_iiiiij = e2.asm.qb).apply(null, arguments);
            }, Dt = e2.dynCall_jii = function() {
              return (Dt = e2.dynCall_jii = e2.asm.rb).apply(null, arguments);
            }, $t = e2.dynCall_viiiiij = function() {
              return ($t = e2.dynCall_viiiiij = e2.asm.sb).apply(null, arguments);
            }, kt = e2.dynCall_vjji = function() {
              return (kt = e2.dynCall_vjji = e2.asm.tb).apply(null, arguments);
            }, Ct = e2.dynCall_viiijjjii = function() {
              return (Ct = e2.dynCall_viiijjjii = e2.asm.ub).apply(null, arguments);
            }, Ft = e2.dynCall_iij = function() {
              return (Ft = e2.dynCall_iij = e2.asm.vb).apply(null, arguments);
            }, Nt = e2.dynCall_ji = function() {
              return (Nt = e2.dynCall_ji = e2.asm.wb).apply(null, arguments);
            }, Lt = e2.dynCall_iiiiiij = function() {
              return (Lt = e2.dynCall_iiiiiij = e2.asm.xb).apply(null, arguments);
            }, Rt = e2.dynCall_iiij = function() {
              return (Rt = e2.dynCall_iiij = e2.asm.yb).apply(null, arguments);
            };
            function jt() {
              function t3() {
                if (!mt && (mt = true, e2.calledRun = true, !I)) {
                  if (Z(R), r2(e2), e2.onRuntimeInitialized && e2.onRuntimeInitialized(), e2.postRun) for ("function" == typeof e2.postRun && (e2.postRun = [e2.postRun]); e2.postRun.length; ) {
                    var t4 = e2.postRun.shift();
                    M.unshift(t4);
                  }
                  Z(M);
                }
              }
              if (!(0 < z2)) {
                if (e2.preRun) for ("function" == typeof e2.preRun && (e2.preRun = [e2.preRun]); e2.preRun.length; ) V();
                Z(L), 0 < z2 || (e2.setStatus ? (e2.setStatus("Running..."), setTimeout((function() {
                  setTimeout((function() {
                    e2.setStatus("");
                  }), 1), t3();
                }), 1)) : t3());
              }
            }
            if (e2.UTF8ToString = $, e2.stringToUTF8 = function(t3, e3, n2) {
              return k(t3, O, e3, n2);
            }, e2.lengthBytesUTF8 = C, e2.stackSave = Tt, e2.stackRestore = St, e2.stackAlloc = Ot, H = function t3() {
              mt || jt(), mt || (H = t3);
            }, e2.preInit) for ("function" == typeof e2.preInit && (e2.preInit = [e2.preInit]); 0 < e2.preInit.length; ) e2.preInit.pop()();
            return jt(), t2.ready;
          });
          t.exports = r;
        }, 4537: (t) => {
          t.exports = function(t2, e) {
            for (var n = new Array(arguments.length - 1), r = 0, i2 = 2, o = true; i2 < arguments.length; ) n[r++] = arguments[i2++];
            return new Promise((function(i3, a) {
              n[r] = function(t3) {
                if (o) if (o = false, t3) a(t3);
                else {
                  for (var e2 = new Array(arguments.length - 1), n2 = 0; n2 < e2.length; ) e2[n2++] = arguments[n2];
                  i3.apply(null, e2);
                }
              };
              try {
                t2.apply(e || null, n);
              } catch (t3) {
                o && (o = false, a(t3));
              }
            }));
          };
        }, 7419: (t, e) => {
          var n = e;
          n.length = function(t2) {
            var e2 = t2.length;
            if (!e2) return 0;
            for (var n2 = 0; --e2 % 4 > 1 && "=" === t2.charAt(e2); ) ++n2;
            return Math.ceil(3 * t2.length) / 4 - n2;
          };
          for (var r = new Array(64), i2 = new Array(123), o = 0; o < 64; ) i2[r[o] = o < 26 ? o + 65 : o < 52 ? o + 71 : o < 62 ? o - 4 : o - 59 | 43] = o++;
          n.encode = function(t2, e2, n2) {
            for (var i3, o2 = null, a2 = [], s = 0, u = 0; e2 < n2; ) {
              var c = t2[e2++];
              switch (u) {
                case 0:
                  a2[s++] = r[c >> 2], i3 = (3 & c) << 4, u = 1;
                  break;
                case 1:
                  a2[s++] = r[i3 | c >> 4], i3 = (15 & c) << 2, u = 2;
                  break;
                case 2:
                  a2[s++] = r[i3 | c >> 6], a2[s++] = r[63 & c], u = 0;
              }
              s > 8191 && ((o2 || (o2 = [])).push(String.fromCharCode.apply(String, a2)), s = 0);
            }
            return u && (a2[s++] = r[i3], a2[s++] = 61, 1 === u && (a2[s++] = 61)), o2 ? (s && o2.push(String.fromCharCode.apply(String, a2.slice(0, s))), o2.join("")) : String.fromCharCode.apply(String, a2.slice(0, s));
          };
          var a = "invalid encoding";
          n.decode = function(t2, e2, n2) {
            for (var r2, o2 = n2, s = 0, u = 0; u < t2.length; ) {
              var c = t2.charCodeAt(u++);
              if (61 === c && s > 1) break;
              if (void 0 === (c = i2[c])) throw Error(a);
              switch (s) {
                case 0:
                  r2 = c, s = 1;
                  break;
                case 1:
                  e2[n2++] = r2 << 2 | (48 & c) >> 4, r2 = c, s = 2;
                  break;
                case 2:
                  e2[n2++] = (15 & r2) << 4 | (60 & c) >> 2, r2 = c, s = 3;
                  break;
                case 3:
                  e2[n2++] = (3 & r2) << 6 | c, s = 0;
              }
            }
            if (1 === s) throw Error(a);
            return n2 - o2;
          }, n.test = function(t2) {
            return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t2);
          };
        }, 9211: (t) => {
          function e() {
            this._listeners = {};
          }
          t.exports = e, e.prototype.on = function(t2, e2, n) {
            return (this._listeners[t2] || (this._listeners[t2] = [])).push({ fn: e2, ctx: n || this }), this;
          }, e.prototype.off = function(t2, e2) {
            if (void 0 === t2) this._listeners = {};
            else if (void 0 === e2) this._listeners[t2] = [];
            else for (var n = this._listeners[t2], r = 0; r < n.length; ) n[r].fn === e2 ? n.splice(r, 1) : ++r;
            return this;
          }, e.prototype.emit = function(t2) {
            var e2 = this._listeners[t2];
            if (e2) {
              for (var n = [], r = 1; r < arguments.length; ) n.push(arguments[r++]);
              for (r = 0; r < e2.length; ) e2[r].fn.apply(e2[r++].ctx, n);
            }
            return this;
          };
        }, 945: (t) => {
          function e(t2) {
            return "undefined" != typeof Float32Array ? (function() {
              var e2 = new Float32Array([-0]), n2 = new Uint8Array(e2.buffer), r2 = 128 === n2[3];
              function i3(t3, r3, i4) {
                e2[0] = t3, r3[i4] = n2[0], r3[i4 + 1] = n2[1], r3[i4 + 2] = n2[2], r3[i4 + 3] = n2[3];
              }
              function o2(t3, r3, i4) {
                e2[0] = t3, r3[i4] = n2[3], r3[i4 + 1] = n2[2], r3[i4 + 2] = n2[1], r3[i4 + 3] = n2[0];
              }
              function a(t3, r3) {
                return n2[0] = t3[r3], n2[1] = t3[r3 + 1], n2[2] = t3[r3 + 2], n2[3] = t3[r3 + 3], e2[0];
              }
              function s(t3, r3) {
                return n2[3] = t3[r3], n2[2] = t3[r3 + 1], n2[1] = t3[r3 + 2], n2[0] = t3[r3 + 3], e2[0];
              }
              t2.writeFloatLE = r2 ? i3 : o2, t2.writeFloatBE = r2 ? o2 : i3, t2.readFloatLE = r2 ? a : s, t2.readFloatBE = r2 ? s : a;
            })() : (function() {
              function e2(t3, e3, n2, r2) {
                var i3 = e3 < 0 ? 1 : 0;
                if (i3 && (e3 = -e3), 0 === e3) t3(1 / e3 > 0 ? 0 : 2147483648, n2, r2);
                else if (isNaN(e3)) t3(2143289344, n2, r2);
                else if (e3 > 34028234663852886e22) t3((i3 << 31 | 2139095040) >>> 0, n2, r2);
                else if (e3 < 11754943508222875e-54) t3((i3 << 31 | Math.round(e3 / 1401298464324817e-60)) >>> 0, n2, r2);
                else {
                  var o2 = Math.floor(Math.log(e3) / Math.LN2);
                  t3((i3 << 31 | o2 + 127 << 23 | 8388607 & Math.round(e3 * Math.pow(2, -o2) * 8388608)) >>> 0, n2, r2);
                }
              }
              function a(t3, e3, n2) {
                var r2 = t3(e3, n2), i3 = 2 * (r2 >> 31) + 1, o2 = r2 >>> 23 & 255, a2 = 8388607 & r2;
                return 255 === o2 ? a2 ? NaN : i3 * (1 / 0) : 0 === o2 ? 1401298464324817e-60 * i3 * a2 : i3 * Math.pow(2, o2 - 150) * (a2 + 8388608);
              }
              t2.writeFloatLE = e2.bind(null, n), t2.writeFloatBE = e2.bind(null, r), t2.readFloatLE = a.bind(null, i2), t2.readFloatBE = a.bind(null, o);
            })(), "undefined" != typeof Float64Array ? (function() {
              var e2 = new Float64Array([-0]), n2 = new Uint8Array(e2.buffer), r2 = 128 === n2[7];
              function i3(t3, r3, i4) {
                e2[0] = t3, r3[i4] = n2[0], r3[i4 + 1] = n2[1], r3[i4 + 2] = n2[2], r3[i4 + 3] = n2[3], r3[i4 + 4] = n2[4], r3[i4 + 5] = n2[5], r3[i4 + 6] = n2[6], r3[i4 + 7] = n2[7];
              }
              function o2(t3, r3, i4) {
                e2[0] = t3, r3[i4] = n2[7], r3[i4 + 1] = n2[6], r3[i4 + 2] = n2[5], r3[i4 + 3] = n2[4], r3[i4 + 4] = n2[3], r3[i4 + 5] = n2[2], r3[i4 + 6] = n2[1], r3[i4 + 7] = n2[0];
              }
              function a(t3, r3) {
                return n2[0] = t3[r3], n2[1] = t3[r3 + 1], n2[2] = t3[r3 + 2], n2[3] = t3[r3 + 3], n2[4] = t3[r3 + 4], n2[5] = t3[r3 + 5], n2[6] = t3[r3 + 6], n2[7] = t3[r3 + 7], e2[0];
              }
              function s(t3, r3) {
                return n2[7] = t3[r3], n2[6] = t3[r3 + 1], n2[5] = t3[r3 + 2], n2[4] = t3[r3 + 3], n2[3] = t3[r3 + 4], n2[2] = t3[r3 + 5], n2[1] = t3[r3 + 6], n2[0] = t3[r3 + 7], e2[0];
              }
              t2.writeDoubleLE = r2 ? i3 : o2, t2.writeDoubleBE = r2 ? o2 : i3, t2.readDoubleLE = r2 ? a : s, t2.readDoubleBE = r2 ? s : a;
            })() : (function() {
              function e2(t3, e3, n2, r2, i3, o2) {
                var a2 = r2 < 0 ? 1 : 0;
                if (a2 && (r2 = -r2), 0 === r2) t3(0, i3, o2 + e3), t3(1 / r2 > 0 ? 0 : 2147483648, i3, o2 + n2);
                else if (isNaN(r2)) t3(0, i3, o2 + e3), t3(2146959360, i3, o2 + n2);
                else if (r2 > 17976931348623157e292) t3(0, i3, o2 + e3), t3((a2 << 31 | 2146435072) >>> 0, i3, o2 + n2);
                else {
                  var s;
                  if (r2 < 22250738585072014e-324) t3((s = r2 / 5e-324) >>> 0, i3, o2 + e3), t3((a2 << 31 | s / 4294967296) >>> 0, i3, o2 + n2);
                  else {
                    var u = Math.floor(Math.log(r2) / Math.LN2);
                    1024 === u && (u = 1023), t3(4503599627370496 * (s = r2 * Math.pow(2, -u)) >>> 0, i3, o2 + e3), t3((a2 << 31 | u + 1023 << 20 | 1048576 * s & 1048575) >>> 0, i3, o2 + n2);
                  }
                }
              }
              function a(t3, e3, n2, r2, i3) {
                var o2 = t3(r2, i3 + e3), a2 = t3(r2, i3 + n2), s = 2 * (a2 >> 31) + 1, u = a2 >>> 20 & 2047, c = 4294967296 * (1048575 & a2) + o2;
                return 2047 === u ? c ? NaN : s * (1 / 0) : 0 === u ? 5e-324 * s * c : s * Math.pow(2, u - 1075) * (c + 4503599627370496);
              }
              t2.writeDoubleLE = e2.bind(null, n, 0, 4), t2.writeDoubleBE = e2.bind(null, r, 4, 0), t2.readDoubleLE = a.bind(null, i2, 0, 4), t2.readDoubleBE = a.bind(null, o, 4, 0);
            })(), t2;
          }
          function n(t2, e2, n2) {
            e2[n2] = 255 & t2, e2[n2 + 1] = t2 >>> 8 & 255, e2[n2 + 2] = t2 >>> 16 & 255, e2[n2 + 3] = t2 >>> 24;
          }
          function r(t2, e2, n2) {
            e2[n2] = t2 >>> 24, e2[n2 + 1] = t2 >>> 16 & 255, e2[n2 + 2] = t2 >>> 8 & 255, e2[n2 + 3] = 255 & t2;
          }
          function i2(t2, e2) {
            return (t2[e2] | t2[e2 + 1] << 8 | t2[e2 + 2] << 16 | t2[e2 + 3] << 24) >>> 0;
          }
          function o(t2, e2) {
            return (t2[e2] << 24 | t2[e2 + 1] << 16 | t2[e2 + 2] << 8 | t2[e2 + 3]) >>> 0;
          }
          t.exports = e(e);
        }, 7199: (module) => {
          function inquire(moduleName) {
            try {
              var mod = eval("quire".replace(/^/, "re"))(moduleName);
              if (mod && (mod.length || Object.keys(mod).length)) return mod;
            } catch (t) {
            }
            return null;
          }
          module.exports = inquire;
        }, 6662: (t) => {
          t.exports = function(t2, e, n) {
            var r = n || 8192, i2 = r >>> 1, o = null, a = r;
            return function(n2) {
              if (n2 < 1 || n2 > i2) return t2(n2);
              a + n2 > r && (o = t2(r), a = 0);
              var s = e.call(o, a, a += n2);
              return 7 & a && (a = 1 + (7 | a)), s;
            };
          };
        }, 4997: (t, e) => {
          var n = e;
          n.length = function(t2) {
            for (var e2 = 0, n2 = 0, r = 0; r < t2.length; ++r) (n2 = t2.charCodeAt(r)) < 128 ? e2 += 1 : n2 < 2048 ? e2 += 2 : 55296 == (64512 & n2) && 56320 == (64512 & t2.charCodeAt(r + 1)) ? (++r, e2 += 4) : e2 += 3;
            return e2;
          }, n.read = function(t2, e2, n2) {
            if (n2 - e2 < 1) return "";
            for (var r, i2 = null, o = [], a = 0; e2 < n2; ) (r = t2[e2++]) < 128 ? o[a++] = r : r > 191 && r < 224 ? o[a++] = (31 & r) << 6 | 63 & t2[e2++] : r > 239 && r < 365 ? (r = ((7 & r) << 18 | (63 & t2[e2++]) << 12 | (63 & t2[e2++]) << 6 | 63 & t2[e2++]) - 65536, o[a++] = 55296 + (r >> 10), o[a++] = 56320 + (1023 & r)) : o[a++] = (15 & r) << 12 | (63 & t2[e2++]) << 6 | 63 & t2[e2++], a > 8191 && ((i2 || (i2 = [])).push(String.fromCharCode.apply(String, o)), a = 0);
            return i2 ? (a && i2.push(String.fromCharCode.apply(String, o.slice(0, a))), i2.join("")) : String.fromCharCode.apply(String, o.slice(0, a));
          }, n.write = function(t2, e2, n2) {
            for (var r, i2, o = n2, a = 0; a < t2.length; ++a) (r = t2.charCodeAt(a)) < 128 ? e2[n2++] = r : r < 2048 ? (e2[n2++] = r >> 6 | 192, e2[n2++] = 63 & r | 128) : 55296 == (64512 & r) && 56320 == (64512 & (i2 = t2.charCodeAt(a + 1))) ? (r = 65536 + ((1023 & r) << 10) + (1023 & i2), ++a, e2[n2++] = r >> 18 | 240, e2[n2++] = r >> 12 & 63 | 128, e2[n2++] = r >> 6 & 63 | 128, e2[n2++] = 63 & r | 128) : (e2[n2++] = r >> 12 | 224, e2[n2++] = r >> 6 & 63 | 128, e2[n2++] = 63 & r | 128);
            return n2 - o;
          };
        }, 3442: (t, e) => {
          e.__esModule = true;
          var n = (function() {
            function t2(e2) {
              if (!e2) throw new TypeError("Invalid argument; `value` has no value.");
              this.value = t2.EMPTY, e2 && t2.isGuid(e2) && (this.value = e2);
            }
            return t2.isGuid = function(e2) {
              var n2 = e2.toString();
              return e2 && (e2 instanceof t2 || t2.validator.test(n2));
            }, t2.create = function() {
              return new t2([t2.gen(2), t2.gen(1), t2.gen(1), t2.gen(1), t2.gen(3)].join("-"));
            }, t2.createEmpty = function() {
              return new t2("emptyguid");
            }, t2.parse = function(e2) {
              return new t2(e2);
            }, t2.raw = function() {
              return [t2.gen(2), t2.gen(1), t2.gen(1), t2.gen(1), t2.gen(3)].join("-");
            }, t2.gen = function(t3) {
              for (var e2 = "", n2 = 0; n2 < t3; n2++) e2 += (65536 * (1 + Math.random()) | 0).toString(16).substring(1);
              return e2;
            }, t2.prototype.equals = function(e2) {
              return t2.isGuid(e2) && this.value === e2.toString();
            }, t2.prototype.isEmpty = function() {
              return this.value === t2.EMPTY;
            }, t2.prototype.toString = function() {
              return this.value;
            }, t2.prototype.toJSON = function() {
              return { value: this.value };
            }, t2.validator = new RegExp("^[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}$", "i"), t2.EMPTY = "00000000-0000-0000-0000-000000000000", t2;
          })();
          e.Guid = n;
        }, 3720: (t) => {
          t.exports = n;
          var e = null;
          try {
            e = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports;
          } catch (t2) {
          }
          function n(t2, e2, n2) {
            this.low = 0 | t2, this.high = 0 | e2, this.unsigned = !!n2;
          }
          function r(t2) {
            return true === (t2 && t2.__isLong__);
          }
          n.prototype.__isLong__, Object.defineProperty(n.prototype, "__isLong__", { value: true }), n.isLong = r;
          var i2 = {}, o = {};
          function a(t2, e2) {
            var n2, r2, a2;
            return e2 ? (a2 = 0 <= (t2 >>>= 0) && t2 < 256) && (r2 = o[t2]) ? r2 : (n2 = u(t2, (0 | t2) < 0 ? -1 : 0, true), a2 && (o[t2] = n2), n2) : (a2 = -128 <= (t2 |= 0) && t2 < 128) && (r2 = i2[t2]) ? r2 : (n2 = u(t2, t2 < 0 ? -1 : 0, false), a2 && (i2[t2] = n2), n2);
          }
          function s(t2, e2) {
            if (isNaN(t2)) return e2 ? m : b;
            if (e2) {
              if (t2 < 0) return m;
              if (t2 >= d) return x;
            } else {
              if (t2 <= -h) return T;
              if (t2 + 1 >= h) return w;
            }
            return t2 < 0 ? s(-t2, e2).neg() : u(t2 % f | 0, t2 / f | 0, e2);
          }
          function u(t2, e2, r2) {
            return new n(t2, e2, r2);
          }
          n.fromInt = a, n.fromNumber = s, n.fromBits = u;
          var c = Math.pow;
          function l(t2, e2, n2) {
            if (0 === t2.length) throw Error("empty string");
            if ("NaN" === t2 || "Infinity" === t2 || "+Infinity" === t2 || "-Infinity" === t2) return b;
            if ("number" == typeof e2 ? (n2 = e2, e2 = false) : e2 = !!e2, (n2 = n2 || 10) < 2 || 36 < n2) throw RangeError("radix");
            var r2;
            if ((r2 = t2.indexOf("-")) > 0) throw Error("interior hyphen");
            if (0 === r2) return l(t2.substring(1), e2, n2).neg();
            for (var i3 = s(c(n2, 8)), o2 = b, a2 = 0; a2 < t2.length; a2 += 8) {
              var u2 = Math.min(8, t2.length - a2), p2 = parseInt(t2.substring(a2, a2 + u2), n2);
              if (u2 < 8) {
                var f2 = s(c(n2, u2));
                o2 = o2.mul(f2).add(s(p2));
              } else o2 = (o2 = o2.mul(i3)).add(s(p2));
            }
            return o2.unsigned = e2, o2;
          }
          function p(t2, e2) {
            return "number" == typeof t2 ? s(t2, e2) : "string" == typeof t2 ? l(t2, e2) : u(t2.low, t2.high, "boolean" == typeof e2 ? e2 : t2.unsigned);
          }
          n.fromString = l, n.fromValue = p;
          var f = 4294967296, d = f * f, h = d / 2, g = a(1 << 24), b = a(0);
          n.ZERO = b;
          var m = a(0, true);
          n.UZERO = m;
          var y = a(1);
          n.ONE = y;
          var _ = a(1, true);
          n.UONE = _;
          var v = a(-1);
          n.NEG_ONE = v;
          var w = u(-1, 2147483647, false);
          n.MAX_VALUE = w;
          var x = u(-1, -1, true);
          n.MAX_UNSIGNED_VALUE = x;
          var T = u(0, -2147483648, false);
          n.MIN_VALUE = T;
          var S = n.prototype;
          S.toInt = function() {
            return this.unsigned ? this.low >>> 0 : this.low;
          }, S.toNumber = function() {
            return this.unsigned ? (this.high >>> 0) * f + (this.low >>> 0) : this.high * f + (this.low >>> 0);
          }, S.toString = function(t2) {
            if ((t2 = t2 || 10) < 2 || 36 < t2) throw RangeError("radix");
            if (this.isZero()) return "0";
            if (this.isNegative()) {
              if (this.eq(T)) {
                var e2 = s(t2), n2 = this.div(e2), r2 = n2.mul(e2).sub(this);
                return n2.toString(t2) + r2.toInt().toString(t2);
              }
              return "-" + this.neg().toString(t2);
            }
            for (var i3 = s(c(t2, 6), this.unsigned), o2 = this, a2 = ""; ; ) {
              var u2 = o2.div(i3), l2 = (o2.sub(u2.mul(i3)).toInt() >>> 0).toString(t2);
              if ((o2 = u2).isZero()) return l2 + a2;
              for (; l2.length < 6; ) l2 = "0" + l2;
              a2 = "" + l2 + a2;
            }
          }, S.getHighBits = function() {
            return this.high;
          }, S.getHighBitsUnsigned = function() {
            return this.high >>> 0;
          }, S.getLowBits = function() {
            return this.low;
          }, S.getLowBitsUnsigned = function() {
            return this.low >>> 0;
          }, S.getNumBitsAbs = function() {
            if (this.isNegative()) return this.eq(T) ? 64 : this.neg().getNumBitsAbs();
            for (var t2 = 0 != this.high ? this.high : this.low, e2 = 31; e2 > 0 && 0 == (t2 & 1 << e2); e2--) ;
            return 0 != this.high ? e2 + 33 : e2 + 1;
          }, S.isZero = function() {
            return 0 === this.high && 0 === this.low;
          }, S.eqz = S.isZero, S.isNegative = function() {
            return !this.unsigned && this.high < 0;
          }, S.isPositive = function() {
            return this.unsigned || this.high >= 0;
          }, S.isOdd = function() {
            return 1 == (1 & this.low);
          }, S.isEven = function() {
            return 0 == (1 & this.low);
          }, S.equals = function(t2) {
            return r(t2) || (t2 = p(t2)), (this.unsigned === t2.unsigned || this.high >>> 31 != 1 || t2.high >>> 31 != 1) && this.high === t2.high && this.low === t2.low;
          }, S.eq = S.equals, S.notEquals = function(t2) {
            return !this.eq(t2);
          }, S.neq = S.notEquals, S.ne = S.notEquals, S.lessThan = function(t2) {
            return this.comp(t2) < 0;
          }, S.lt = S.lessThan, S.lessThanOrEqual = function(t2) {
            return this.comp(t2) <= 0;
          }, S.lte = S.lessThanOrEqual, S.le = S.lessThanOrEqual, S.greaterThan = function(t2) {
            return this.comp(t2) > 0;
          }, S.gt = S.greaterThan, S.greaterThanOrEqual = function(t2) {
            return this.comp(t2) >= 0;
          }, S.gte = S.greaterThanOrEqual, S.ge = S.greaterThanOrEqual, S.compare = function(t2) {
            if (r(t2) || (t2 = p(t2)), this.eq(t2)) return 0;
            var e2 = this.isNegative(), n2 = t2.isNegative();
            return e2 && !n2 ? -1 : !e2 && n2 ? 1 : this.unsigned ? t2.high >>> 0 > this.high >>> 0 || t2.high === this.high && t2.low >>> 0 > this.low >>> 0 ? -1 : 1 : this.sub(t2).isNegative() ? -1 : 1;
          }, S.comp = S.compare, S.negate = function() {
            return !this.unsigned && this.eq(T) ? T : this.not().add(y);
          }, S.neg = S.negate, S.add = function(t2) {
            r(t2) || (t2 = p(t2));
            var e2 = this.high >>> 16, n2 = 65535 & this.high, i3 = this.low >>> 16, o2 = 65535 & this.low, a2 = t2.high >>> 16, s2 = 65535 & t2.high, c2 = t2.low >>> 16, l2 = 0, f2 = 0, d2 = 0, h2 = 0;
            return d2 += (h2 += o2 + (65535 & t2.low)) >>> 16, f2 += (d2 += i3 + c2) >>> 16, l2 += (f2 += n2 + s2) >>> 16, l2 += e2 + a2, u((d2 &= 65535) << 16 | (h2 &= 65535), (l2 &= 65535) << 16 | (f2 &= 65535), this.unsigned);
          }, S.subtract = function(t2) {
            return r(t2) || (t2 = p(t2)), this.add(t2.neg());
          }, S.sub = S.subtract, S.multiply = function(t2) {
            if (this.isZero()) return b;
            if (r(t2) || (t2 = p(t2)), e) return u(e.mul(this.low, this.high, t2.low, t2.high), e.get_high(), this.unsigned);
            if (t2.isZero()) return b;
            if (this.eq(T)) return t2.isOdd() ? T : b;
            if (t2.eq(T)) return this.isOdd() ? T : b;
            if (this.isNegative()) return t2.isNegative() ? this.neg().mul(t2.neg()) : this.neg().mul(t2).neg();
            if (t2.isNegative()) return this.mul(t2.neg()).neg();
            if (this.lt(g) && t2.lt(g)) return s(this.toNumber() * t2.toNumber(), this.unsigned);
            var n2 = this.high >>> 16, i3 = 65535 & this.high, o2 = this.low >>> 16, a2 = 65535 & this.low, c2 = t2.high >>> 16, l2 = 65535 & t2.high, f2 = t2.low >>> 16, d2 = 65535 & t2.low, h2 = 0, m2 = 0, y2 = 0, _2 = 0;
            return y2 += (_2 += a2 * d2) >>> 16, m2 += (y2 += o2 * d2) >>> 16, y2 &= 65535, m2 += (y2 += a2 * f2) >>> 16, h2 += (m2 += i3 * d2) >>> 16, m2 &= 65535, h2 += (m2 += o2 * f2) >>> 16, m2 &= 65535, h2 += (m2 += a2 * l2) >>> 16, h2 += n2 * d2 + i3 * f2 + o2 * l2 + a2 * c2, u((y2 &= 65535) << 16 | (_2 &= 65535), (h2 &= 65535) << 16 | (m2 &= 65535), this.unsigned);
          }, S.mul = S.multiply, S.divide = function(t2) {
            if (r(t2) || (t2 = p(t2)), t2.isZero()) throw Error("division by zero");
            var n2, i3, o2;
            if (e) return this.unsigned || -2147483648 !== this.high || -1 !== t2.low || -1 !== t2.high ? u((this.unsigned ? e.div_u : e.div_s)(this.low, this.high, t2.low, t2.high), e.get_high(), this.unsigned) : this;
            if (this.isZero()) return this.unsigned ? m : b;
            if (this.unsigned) {
              if (t2.unsigned || (t2 = t2.toUnsigned()), t2.gt(this)) return m;
              if (t2.gt(this.shru(1))) return _;
              o2 = m;
            } else {
              if (this.eq(T)) return t2.eq(y) || t2.eq(v) ? T : t2.eq(T) ? y : (n2 = this.shr(1).div(t2).shl(1)).eq(b) ? t2.isNegative() ? y : v : (i3 = this.sub(t2.mul(n2)), o2 = n2.add(i3.div(t2)));
              if (t2.eq(T)) return this.unsigned ? m : b;
              if (this.isNegative()) return t2.isNegative() ? this.neg().div(t2.neg()) : this.neg().div(t2).neg();
              if (t2.isNegative()) return this.div(t2.neg()).neg();
              o2 = b;
            }
            for (i3 = this; i3.gte(t2); ) {
              n2 = Math.max(1, Math.floor(i3.toNumber() / t2.toNumber()));
              for (var a2 = Math.ceil(Math.log(n2) / Math.LN2), l2 = a2 <= 48 ? 1 : c(2, a2 - 48), f2 = s(n2), d2 = f2.mul(t2); d2.isNegative() || d2.gt(i3); ) d2 = (f2 = s(n2 -= l2, this.unsigned)).mul(t2);
              f2.isZero() && (f2 = y), o2 = o2.add(f2), i3 = i3.sub(d2);
            }
            return o2;
          }, S.div = S.divide, S.modulo = function(t2) {
            return r(t2) || (t2 = p(t2)), e ? u((this.unsigned ? e.rem_u : e.rem_s)(this.low, this.high, t2.low, t2.high), e.get_high(), this.unsigned) : this.sub(this.div(t2).mul(t2));
          }, S.mod = S.modulo, S.rem = S.modulo, S.not = function() {
            return u(~this.low, ~this.high, this.unsigned);
          }, S.and = function(t2) {
            return r(t2) || (t2 = p(t2)), u(this.low & t2.low, this.high & t2.high, this.unsigned);
          }, S.or = function(t2) {
            return r(t2) || (t2 = p(t2)), u(this.low | t2.low, this.high | t2.high, this.unsigned);
          }, S.xor = function(t2) {
            return r(t2) || (t2 = p(t2)), u(this.low ^ t2.low, this.high ^ t2.high, this.unsigned);
          }, S.shiftLeft = function(t2) {
            return r(t2) && (t2 = t2.toInt()), 0 == (t2 &= 63) ? this : t2 < 32 ? u(this.low << t2, this.high << t2 | this.low >>> 32 - t2, this.unsigned) : u(0, this.low << t2 - 32, this.unsigned);
          }, S.shl = S.shiftLeft, S.shiftRight = function(t2) {
            return r(t2) && (t2 = t2.toInt()), 0 == (t2 &= 63) ? this : t2 < 32 ? u(this.low >>> t2 | this.high << 32 - t2, this.high >> t2, this.unsigned) : u(this.high >> t2 - 32, this.high >= 0 ? 0 : -1, this.unsigned);
          }, S.shr = S.shiftRight, S.shiftRightUnsigned = function(t2) {
            if (r(t2) && (t2 = t2.toInt()), 0 == (t2 &= 63)) return this;
            var e2 = this.high;
            return t2 < 32 ? u(this.low >>> t2 | e2 << 32 - t2, e2 >>> t2, this.unsigned) : u(32 === t2 ? e2 : e2 >>> t2 - 32, 0, this.unsigned);
          }, S.shru = S.shiftRightUnsigned, S.shr_u = S.shiftRightUnsigned, S.toSigned = function() {
            return this.unsigned ? u(this.low, this.high, false) : this;
          }, S.toUnsigned = function() {
            return this.unsigned ? this : u(this.low, this.high, true);
          }, S.toBytes = function(t2) {
            return t2 ? this.toBytesLE() : this.toBytesBE();
          }, S.toBytesLE = function() {
            var t2 = this.high, e2 = this.low;
            return [255 & e2, e2 >>> 8 & 255, e2 >>> 16 & 255, e2 >>> 24, 255 & t2, t2 >>> 8 & 255, t2 >>> 16 & 255, t2 >>> 24];
          }, S.toBytesBE = function() {
            var t2 = this.high, e2 = this.low;
            return [t2 >>> 24, t2 >>> 16 & 255, t2 >>> 8 & 255, 255 & t2, e2 >>> 24, e2 >>> 16 & 255, e2 >>> 8 & 255, 255 & e2];
          }, n.fromBytes = function(t2, e2, r2) {
            return r2 ? n.fromBytesLE(t2, e2) : n.fromBytesBE(t2, e2);
          }, n.fromBytesLE = function(t2, e2) {
            return new n(t2[0] | t2[1] << 8 | t2[2] << 16 | t2[3] << 24, t2[4] | t2[5] << 8 | t2[6] << 16 | t2[7] << 24, e2);
          }, n.fromBytesBE = function(t2, e2) {
            return new n(t2[4] << 24 | t2[5] << 16 | t2[6] << 8 | t2[7], t2[0] << 24 | t2[1] << 16 | t2[2] << 8 | t2[3], e2);
          };
        }, 1446: (t, e, n) => {
          var r, i2, o, a = n(2100), s = a.Reader, u = a.Writer, c = a.util, l = a.roots.default || (a.roots.default = {});
          l.onnx = ((o = {}).Version = (r = {}, (i2 = Object.create(r))[r[0] = "_START_VERSION"] = 0, i2[r[1] = "IR_VERSION_2017_10_10"] = 1, i2[r[2] = "IR_VERSION_2017_10_30"] = 2, i2[r[3] = "IR_VERSION_2017_11_3"] = 3, i2[r[4] = "IR_VERSION_2019_1_22"] = 4, i2[r[5] = "IR_VERSION"] = 5, i2), o.AttributeProto = (function() {
            function t2(t3) {
              if (this.floats = [], this.ints = [], this.strings = [], this.tensors = [], this.graphs = [], t3) for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2) null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]);
            }
            return t2.prototype.name = "", t2.prototype.refAttrName = "", t2.prototype.docString = "", t2.prototype.type = 0, t2.prototype.f = 0, t2.prototype.i = c.Long ? c.Long.fromBits(0, 0, false) : 0, t2.prototype.s = c.newBuffer([]), t2.prototype.t = null, t2.prototype.g = null, t2.prototype.floats = c.emptyArray, t2.prototype.ints = c.emptyArray, t2.prototype.strings = c.emptyArray, t2.prototype.tensors = c.emptyArray, t2.prototype.graphs = c.emptyArray, t2.create = function(e2) {
              return new t2(e2);
            }, t2.encode = function(t3, e2) {
              if (e2 || (e2 = u.create()), null != t3.name && t3.hasOwnProperty("name") && e2.uint32(10).string(t3.name), null != t3.f && t3.hasOwnProperty("f") && e2.uint32(21).float(t3.f), null != t3.i && t3.hasOwnProperty("i") && e2.uint32(24).int64(t3.i), null != t3.s && t3.hasOwnProperty("s") && e2.uint32(34).bytes(t3.s), null != t3.t && t3.hasOwnProperty("t") && l.onnx.TensorProto.encode(t3.t, e2.uint32(42).fork()).ldelim(), null != t3.g && t3.hasOwnProperty("g") && l.onnx.GraphProto.encode(t3.g, e2.uint32(50).fork()).ldelim(), null != t3.floats && t3.floats.length) {
                e2.uint32(58).fork();
                for (var n2 = 0; n2 < t3.floats.length; ++n2) e2.float(t3.floats[n2]);
                e2.ldelim();
              }
              if (null != t3.ints && t3.ints.length) {
                for (e2.uint32(66).fork(), n2 = 0; n2 < t3.ints.length; ++n2) e2.int64(t3.ints[n2]);
                e2.ldelim();
              }
              if (null != t3.strings && t3.strings.length) for (n2 = 0; n2 < t3.strings.length; ++n2) e2.uint32(74).bytes(t3.strings[n2]);
              if (null != t3.tensors && t3.tensors.length) for (n2 = 0; n2 < t3.tensors.length; ++n2) l.onnx.TensorProto.encode(t3.tensors[n2], e2.uint32(82).fork()).ldelim();
              if (null != t3.graphs && t3.graphs.length) for (n2 = 0; n2 < t3.graphs.length; ++n2) l.onnx.GraphProto.encode(t3.graphs[n2], e2.uint32(90).fork()).ldelim();
              return null != t3.docString && t3.hasOwnProperty("docString") && e2.uint32(106).string(t3.docString), null != t3.type && t3.hasOwnProperty("type") && e2.uint32(160).int32(t3.type), null != t3.refAttrName && t3.hasOwnProperty("refAttrName") && e2.uint32(170).string(t3.refAttrName), e2;
            }, t2.encodeDelimited = function(t3, e2) {
              return this.encode(t3, e2).ldelim();
            }, t2.decode = function(t3, e2) {
              t3 instanceof s || (t3 = s.create(t3));
              for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.AttributeProto(); t3.pos < n2; ) {
                var i3 = t3.uint32();
                switch (i3 >>> 3) {
                  case 1:
                    r2.name = t3.string();
                    break;
                  case 21:
                    r2.refAttrName = t3.string();
                    break;
                  case 13:
                    r2.docString = t3.string();
                    break;
                  case 20:
                    r2.type = t3.int32();
                    break;
                  case 2:
                    r2.f = t3.float();
                    break;
                  case 3:
                    r2.i = t3.int64();
                    break;
                  case 4:
                    r2.s = t3.bytes();
                    break;
                  case 5:
                    r2.t = l.onnx.TensorProto.decode(t3, t3.uint32());
                    break;
                  case 6:
                    r2.g = l.onnx.GraphProto.decode(t3, t3.uint32());
                    break;
                  case 7:
                    if (r2.floats && r2.floats.length || (r2.floats = []), 2 == (7 & i3)) for (var o2 = t3.uint32() + t3.pos; t3.pos < o2; ) r2.floats.push(t3.float());
                    else r2.floats.push(t3.float());
                    break;
                  case 8:
                    if (r2.ints && r2.ints.length || (r2.ints = []), 2 == (7 & i3)) for (o2 = t3.uint32() + t3.pos; t3.pos < o2; ) r2.ints.push(t3.int64());
                    else r2.ints.push(t3.int64());
                    break;
                  case 9:
                    r2.strings && r2.strings.length || (r2.strings = []), r2.strings.push(t3.bytes());
                    break;
                  case 10:
                    r2.tensors && r2.tensors.length || (r2.tensors = []), r2.tensors.push(l.onnx.TensorProto.decode(t3, t3.uint32()));
                    break;
                  case 11:
                    r2.graphs && r2.graphs.length || (r2.graphs = []), r2.graphs.push(l.onnx.GraphProto.decode(t3, t3.uint32()));
                    break;
                  default:
                    t3.skipType(7 & i3);
                }
              }
              return r2;
            }, t2.decodeDelimited = function(t3) {
              return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32());
            }, t2.verify = function(t3) {
              if ("object" != typeof t3 || null === t3) return "object expected";
              if (null != t3.name && t3.hasOwnProperty("name") && !c.isString(t3.name)) return "name: string expected";
              if (null != t3.refAttrName && t3.hasOwnProperty("refAttrName") && !c.isString(t3.refAttrName)) return "refAttrName: string expected";
              if (null != t3.docString && t3.hasOwnProperty("docString") && !c.isString(t3.docString)) return "docString: string expected";
              if (null != t3.type && t3.hasOwnProperty("type")) switch (t3.type) {
                default:
                  return "type: enum value expected";
                case 0:
                case 1:
                case 2:
                case 3:
                case 4:
                case 5:
                case 6:
                case 7:
                case 8:
                case 9:
                case 10:
              }
              if (null != t3.f && t3.hasOwnProperty("f") && "number" != typeof t3.f) return "f: number expected";
              if (null != t3.i && t3.hasOwnProperty("i") && !(c.isInteger(t3.i) || t3.i && c.isInteger(t3.i.low) && c.isInteger(t3.i.high))) return "i: integer|Long expected";
              if (null != t3.s && t3.hasOwnProperty("s") && !(t3.s && "number" == typeof t3.s.length || c.isString(t3.s))) return "s: buffer expected";
              if (null != t3.t && t3.hasOwnProperty("t") && (n2 = l.onnx.TensorProto.verify(t3.t))) return "t." + n2;
              if (null != t3.g && t3.hasOwnProperty("g") && (n2 = l.onnx.GraphProto.verify(t3.g))) return "g." + n2;
              if (null != t3.floats && t3.hasOwnProperty("floats")) {
                if (!Array.isArray(t3.floats)) return "floats: array expected";
                for (var e2 = 0; e2 < t3.floats.length; ++e2) if ("number" != typeof t3.floats[e2]) return "floats: number[] expected";
              }
              if (null != t3.ints && t3.hasOwnProperty("ints")) {
                if (!Array.isArray(t3.ints)) return "ints: array expected";
                for (e2 = 0; e2 < t3.ints.length; ++e2) if (!(c.isInteger(t3.ints[e2]) || t3.ints[e2] && c.isInteger(t3.ints[e2].low) && c.isInteger(t3.ints[e2].high))) return "ints: integer|Long[] expected";
              }
              if (null != t3.strings && t3.hasOwnProperty("strings")) {
                if (!Array.isArray(t3.strings)) return "strings: array expected";
                for (e2 = 0; e2 < t3.strings.length; ++e2) if (!(t3.strings[e2] && "number" == typeof t3.strings[e2].length || c.isString(t3.strings[e2]))) return "strings: buffer[] expected";
              }
              if (null != t3.tensors && t3.hasOwnProperty("tensors")) {
                if (!Array.isArray(t3.tensors)) return "tensors: array expected";
                for (e2 = 0; e2 < t3.tensors.length; ++e2) if (n2 = l.onnx.TensorProto.verify(t3.tensors[e2])) return "tensors." + n2;
              }
              if (null != t3.graphs && t3.hasOwnProperty("graphs")) {
                if (!Array.isArray(t3.graphs)) return "graphs: array expected";
                for (e2 = 0; e2 < t3.graphs.length; ++e2) {
                  var n2;
                  if (n2 = l.onnx.GraphProto.verify(t3.graphs[e2])) return "graphs." + n2;
                }
              }
              return null;
            }, t2.fromObject = function(t3) {
              if (t3 instanceof l.onnx.AttributeProto) return t3;
              var e2 = new l.onnx.AttributeProto();
              switch (null != t3.name && (e2.name = String(t3.name)), null != t3.refAttrName && (e2.refAttrName = String(t3.refAttrName)), null != t3.docString && (e2.docString = String(t3.docString)), t3.type) {
                case "UNDEFINED":
                case 0:
                  e2.type = 0;
                  break;
                case "FLOAT":
                case 1:
                  e2.type = 1;
                  break;
                case "INT":
                case 2:
                  e2.type = 2;
                  break;
                case "STRING":
                case 3:
                  e2.type = 3;
                  break;
                case "TENSOR":
                case 4:
                  e2.type = 4;
                  break;
                case "GRAPH":
                case 5:
                  e2.type = 5;
                  break;
                case "FLOATS":
                case 6:
                  e2.type = 6;
                  break;
                case "INTS":
                case 7:
                  e2.type = 7;
                  break;
                case "STRINGS":
                case 8:
                  e2.type = 8;
                  break;
                case "TENSORS":
                case 9:
                  e2.type = 9;
                  break;
                case "GRAPHS":
                case 10:
                  e2.type = 10;
              }
              if (null != t3.f && (e2.f = Number(t3.f)), null != t3.i && (c.Long ? (e2.i = c.Long.fromValue(t3.i)).unsigned = false : "string" == typeof t3.i ? e2.i = parseInt(t3.i, 10) : "number" == typeof t3.i ? e2.i = t3.i : "object" == typeof t3.i && (e2.i = new c.LongBits(t3.i.low >>> 0, t3.i.high >>> 0).toNumber())), null != t3.s && ("string" == typeof t3.s ? c.base64.decode(t3.s, e2.s = c.newBuffer(c.base64.length(t3.s)), 0) : t3.s.length && (e2.s = t3.s)), null != t3.t) {
                if ("object" != typeof t3.t) throw TypeError(".onnx.AttributeProto.t: object expected");
                e2.t = l.onnx.TensorProto.fromObject(t3.t);
              }
              if (null != t3.g) {
                if ("object" != typeof t3.g) throw TypeError(".onnx.AttributeProto.g: object expected");
                e2.g = l.onnx.GraphProto.fromObject(t3.g);
              }
              if (t3.floats) {
                if (!Array.isArray(t3.floats)) throw TypeError(".onnx.AttributeProto.floats: array expected");
                e2.floats = [];
                for (var n2 = 0; n2 < t3.floats.length; ++n2) e2.floats[n2] = Number(t3.floats[n2]);
              }
              if (t3.ints) {
                if (!Array.isArray(t3.ints)) throw TypeError(".onnx.AttributeProto.ints: array expected");
                for (e2.ints = [], n2 = 0; n2 < t3.ints.length; ++n2) c.Long ? (e2.ints[n2] = c.Long.fromValue(t3.ints[n2])).unsigned = false : "string" == typeof t3.ints[n2] ? e2.ints[n2] = parseInt(t3.ints[n2], 10) : "number" == typeof t3.ints[n2] ? e2.ints[n2] = t3.ints[n2] : "object" == typeof t3.ints[n2] && (e2.ints[n2] = new c.LongBits(t3.ints[n2].low >>> 0, t3.ints[n2].high >>> 0).toNumber());
              }
              if (t3.strings) {
                if (!Array.isArray(t3.strings)) throw TypeError(".onnx.AttributeProto.strings: array expected");
                for (e2.strings = [], n2 = 0; n2 < t3.strings.length; ++n2) "string" == typeof t3.strings[n2] ? c.base64.decode(t3.strings[n2], e2.strings[n2] = c.newBuffer(c.base64.length(t3.strings[n2])), 0) : t3.strings[n2].length && (e2.strings[n2] = t3.strings[n2]);
              }
              if (t3.tensors) {
                if (!Array.isArray(t3.tensors)) throw TypeError(".onnx.AttributeProto.tensors: array expected");
                for (e2.tensors = [], n2 = 0; n2 < t3.tensors.length; ++n2) {
                  if ("object" != typeof t3.tensors[n2]) throw TypeError(".onnx.AttributeProto.tensors: object expected");
                  e2.tensors[n2] = l.onnx.TensorProto.fromObject(t3.tensors[n2]);
                }
              }
              if (t3.graphs) {
                if (!Array.isArray(t3.graphs)) throw TypeError(".onnx.AttributeProto.graphs: array expected");
                for (e2.graphs = [], n2 = 0; n2 < t3.graphs.length; ++n2) {
                  if ("object" != typeof t3.graphs[n2]) throw TypeError(".onnx.AttributeProto.graphs: object expected");
                  e2.graphs[n2] = l.onnx.GraphProto.fromObject(t3.graphs[n2]);
                }
              }
              return e2;
            }, t2.toObject = function(t3, e2) {
              e2 || (e2 = {});
              var n2 = {};
              if ((e2.arrays || e2.defaults) && (n2.floats = [], n2.ints = [], n2.strings = [], n2.tensors = [], n2.graphs = []), e2.defaults) {
                if (n2.name = "", n2.f = 0, c.Long) {
                  var r2 = new c.Long(0, 0, false);
                  n2.i = e2.longs === String ? r2.toString() : e2.longs === Number ? r2.toNumber() : r2;
                } else n2.i = e2.longs === String ? "0" : 0;
                e2.bytes === String ? n2.s = "" : (n2.s = [], e2.bytes !== Array && (n2.s = c.newBuffer(n2.s))), n2.t = null, n2.g = null, n2.docString = "", n2.type = e2.enums === String ? "UNDEFINED" : 0, n2.refAttrName = "";
              }
              if (null != t3.name && t3.hasOwnProperty("name") && (n2.name = t3.name), null != t3.f && t3.hasOwnProperty("f") && (n2.f = e2.json && !isFinite(t3.f) ? String(t3.f) : t3.f), null != t3.i && t3.hasOwnProperty("i") && ("number" == typeof t3.i ? n2.i = e2.longs === String ? String(t3.i) : t3.i : n2.i = e2.longs === String ? c.Long.prototype.toString.call(t3.i) : e2.longs === Number ? new c.LongBits(t3.i.low >>> 0, t3.i.high >>> 0).toNumber() : t3.i), null != t3.s && t3.hasOwnProperty("s") && (n2.s = e2.bytes === String ? c.base64.encode(t3.s, 0, t3.s.length) : e2.bytes === Array ? Array.prototype.slice.call(t3.s) : t3.s), null != t3.t && t3.hasOwnProperty("t") && (n2.t = l.onnx.TensorProto.toObject(t3.t, e2)), null != t3.g && t3.hasOwnProperty("g") && (n2.g = l.onnx.GraphProto.toObject(t3.g, e2)), t3.floats && t3.floats.length) {
                n2.floats = [];
                for (var i3 = 0; i3 < t3.floats.length; ++i3) n2.floats[i3] = e2.json && !isFinite(t3.floats[i3]) ? String(t3.floats[i3]) : t3.floats[i3];
              }
              if (t3.ints && t3.ints.length) for (n2.ints = [], i3 = 0; i3 < t3.ints.length; ++i3) "number" == typeof t3.ints[i3] ? n2.ints[i3] = e2.longs === String ? String(t3.ints[i3]) : t3.ints[i3] : n2.ints[i3] = e2.longs === String ? c.Long.prototype.toString.call(t3.ints[i3]) : e2.longs === Number ? new c.LongBits(t3.ints[i3].low >>> 0, t3.ints[i3].high >>> 0).toNumber() : t3.ints[i3];
              if (t3.strings && t3.strings.length) for (n2.strings = [], i3 = 0; i3 < t3.strings.length; ++i3) n2.strings[i3] = e2.bytes === String ? c.base64.encode(t3.strings[i3], 0, t3.strings[i3].length) : e2.bytes === Array ? Array.prototype.slice.call(t3.strings[i3]) : t3.strings[i3];
              if (t3.tensors && t3.tensors.length) for (n2.tensors = [], i3 = 0; i3 < t3.tensors.length; ++i3) n2.tensors[i3] = l.onnx.TensorProto.toObject(t3.tensors[i3], e2);
              if (t3.graphs && t3.graphs.length) for (n2.graphs = [], i3 = 0; i3 < t3.graphs.length; ++i3) n2.graphs[i3] = l.onnx.GraphProto.toObject(t3.graphs[i3], e2);
              return null != t3.docString && t3.hasOwnProperty("docString") && (n2.docString = t3.docString), null != t3.type && t3.hasOwnProperty("type") && (n2.type = e2.enums === String ? l.onnx.AttributeProto.AttributeType[t3.type] : t3.type), null != t3.refAttrName && t3.hasOwnProperty("refAttrName") && (n2.refAttrName = t3.refAttrName), n2;
            }, t2.prototype.toJSON = function() {
              return this.constructor.toObject(this, a.util.toJSONOptions);
            }, t2.AttributeType = (function() {
              var t3 = {}, e2 = Object.create(t3);
              return e2[t3[0] = "UNDEFINED"] = 0, e2[t3[1] = "FLOAT"] = 1, e2[t3[2] = "INT"] = 2, e2[t3[3] = "STRING"] = 3, e2[t3[4] = "TENSOR"] = 4, e2[t3[5] = "GRAPH"] = 5, e2[t3[6] = "FLOATS"] = 6, e2[t3[7] = "INTS"] = 7, e2[t3[8] = "STRINGS"] = 8, e2[t3[9] = "TENSORS"] = 9, e2[t3[10] = "GRAPHS"] = 10, e2;
            })(), t2;
          })(), o.ValueInfoProto = (function() {
            function t2(t3) {
              if (t3) for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2) null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]);
            }
            return t2.prototype.name = "", t2.prototype.type = null, t2.prototype.docString = "", t2.create = function(e2) {
              return new t2(e2);
            }, t2.encode = function(t3, e2) {
              return e2 || (e2 = u.create()), null != t3.name && t3.hasOwnProperty("name") && e2.uint32(10).string(t3.name), null != t3.type && t3.hasOwnProperty("type") && l.onnx.TypeProto.encode(t3.type, e2.uint32(18).fork()).ldelim(), null != t3.docString && t3.hasOwnProperty("docString") && e2.uint32(26).string(t3.docString), e2;
            }, t2.encodeDelimited = function(t3, e2) {
              return this.encode(t3, e2).ldelim();
            }, t2.decode = function(t3, e2) {
              t3 instanceof s || (t3 = s.create(t3));
              for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.ValueInfoProto(); t3.pos < n2; ) {
                var i3 = t3.uint32();
                switch (i3 >>> 3) {
                  case 1:
                    r2.name = t3.string();
                    break;
                  case 2:
                    r2.type = l.onnx.TypeProto.decode(t3, t3.uint32());
                    break;
                  case 3:
                    r2.docString = t3.string();
                    break;
                  default:
                    t3.skipType(7 & i3);
                }
              }
              return r2;
            }, t2.decodeDelimited = function(t3) {
              return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32());
            }, t2.verify = function(t3) {
              if ("object" != typeof t3 || null === t3) return "object expected";
              if (null != t3.name && t3.hasOwnProperty("name") && !c.isString(t3.name)) return "name: string expected";
              if (null != t3.type && t3.hasOwnProperty("type")) {
                var e2 = l.onnx.TypeProto.verify(t3.type);
                if (e2) return "type." + e2;
              }
              return null != t3.docString && t3.hasOwnProperty("docString") && !c.isString(t3.docString) ? "docString: string expected" : null;
            }, t2.fromObject = function(t3) {
              if (t3 instanceof l.onnx.ValueInfoProto) return t3;
              var e2 = new l.onnx.ValueInfoProto();
              if (null != t3.name && (e2.name = String(t3.name)), null != t3.type) {
                if ("object" != typeof t3.type) throw TypeError(".onnx.ValueInfoProto.type: object expected");
                e2.type = l.onnx.TypeProto.fromObject(t3.type);
              }
              return null != t3.docString && (e2.docString = String(t3.docString)), e2;
            }, t2.toObject = function(t3, e2) {
              e2 || (e2 = {});
              var n2 = {};
              return e2.defaults && (n2.name = "", n2.type = null, n2.docString = ""), null != t3.name && t3.hasOwnProperty("name") && (n2.name = t3.name), null != t3.type && t3.hasOwnProperty("type") && (n2.type = l.onnx.TypeProto.toObject(t3.type, e2)), null != t3.docString && t3.hasOwnProperty("docString") && (n2.docString = t3.docString), n2;
            }, t2.prototype.toJSON = function() {
              return this.constructor.toObject(this, a.util.toJSONOptions);
            }, t2;
          })(), o.NodeProto = (function() {
            function t2(t3) {
              if (this.input = [], this.output = [], this.attribute = [], t3) for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2) null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]);
            }
            return t2.prototype.input = c.emptyArray, t2.prototype.output = c.emptyArray, t2.prototype.name = "", t2.prototype.opType = "", t2.prototype.domain = "", t2.prototype.attribute = c.emptyArray, t2.prototype.docString = "", t2.create = function(e2) {
              return new t2(e2);
            }, t2.encode = function(t3, e2) {
              if (e2 || (e2 = u.create()), null != t3.input && t3.input.length) for (var n2 = 0; n2 < t3.input.length; ++n2) e2.uint32(10).string(t3.input[n2]);
              if (null != t3.output && t3.output.length) for (n2 = 0; n2 < t3.output.length; ++n2) e2.uint32(18).string(t3.output[n2]);
              if (null != t3.name && t3.hasOwnProperty("name") && e2.uint32(26).string(t3.name), null != t3.opType && t3.hasOwnProperty("opType") && e2.uint32(34).string(t3.opType), null != t3.attribute && t3.attribute.length) for (n2 = 0; n2 < t3.attribute.length; ++n2) l.onnx.AttributeProto.encode(t3.attribute[n2], e2.uint32(42).fork()).ldelim();
              return null != t3.docString && t3.hasOwnProperty("docString") && e2.uint32(50).string(t3.docString), null != t3.domain && t3.hasOwnProperty("domain") && e2.uint32(58).string(t3.domain), e2;
            }, t2.encodeDelimited = function(t3, e2) {
              return this.encode(t3, e2).ldelim();
            }, t2.decode = function(t3, e2) {
              t3 instanceof s || (t3 = s.create(t3));
              for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.NodeProto(); t3.pos < n2; ) {
                var i3 = t3.uint32();
                switch (i3 >>> 3) {
                  case 1:
                    r2.input && r2.input.length || (r2.input = []), r2.input.push(t3.string());
                    break;
                  case 2:
                    r2.output && r2.output.length || (r2.output = []), r2.output.push(t3.string());
                    break;
                  case 3:
                    r2.name = t3.string();
                    break;
                  case 4:
                    r2.opType = t3.string();
                    break;
                  case 7:
                    r2.domain = t3.string();
                    break;
                  case 5:
                    r2.attribute && r2.attribute.length || (r2.attribute = []), r2.attribute.push(l.onnx.AttributeProto.decode(t3, t3.uint32()));
                    break;
                  case 6:
                    r2.docString = t3.string();
                    break;
                  default:
                    t3.skipType(7 & i3);
                }
              }
              return r2;
            }, t2.decodeDelimited = function(t3) {
              return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32());
            }, t2.verify = function(t3) {
              if ("object" != typeof t3 || null === t3) return "object expected";
              if (null != t3.input && t3.hasOwnProperty("input")) {
                if (!Array.isArray(t3.input)) return "input: array expected";
                for (var e2 = 0; e2 < t3.input.length; ++e2) if (!c.isString(t3.input[e2])) return "input: string[] expected";
              }
              if (null != t3.output && t3.hasOwnProperty("output")) {
                if (!Array.isArray(t3.output)) return "output: array expected";
                for (e2 = 0; e2 < t3.output.length; ++e2) if (!c.isString(t3.output[e2])) return "output: string[] expected";
              }
              if (null != t3.name && t3.hasOwnProperty("name") && !c.isString(t3.name)) return "name: string expected";
              if (null != t3.opType && t3.hasOwnProperty("opType") && !c.isString(t3.opType)) return "opType: string expected";
              if (null != t3.domain && t3.hasOwnProperty("domain") && !c.isString(t3.domain)) return "domain: string expected";
              if (null != t3.attribute && t3.hasOwnProperty("attribute")) {
                if (!Array.isArray(t3.attribute)) return "attribute: array expected";
                for (e2 = 0; e2 < t3.attribute.length; ++e2) {
                  var n2 = l.onnx.AttributeProto.verify(t3.attribute[e2]);
                  if (n2) return "attribute." + n2;
                }
              }
              return null != t3.docString && t3.hasOwnProperty("docString") && !c.isString(t3.docString) ? "docString: string expected" : null;
            }, t2.fromObject = function(t3) {
              if (t3 instanceof l.onnx.NodeProto) return t3;
              var e2 = new l.onnx.NodeProto();
              if (t3.input) {
                if (!Array.isArray(t3.input)) throw TypeError(".onnx.NodeProto.input: array expected");
                e2.input = [];
                for (var n2 = 0; n2 < t3.input.length; ++n2) e2.input[n2] = String(t3.input[n2]);
              }
              if (t3.output) {
                if (!Array.isArray(t3.output)) throw TypeError(".onnx.NodeProto.output: array expected");
                for (e2.output = [], n2 = 0; n2 < t3.output.length; ++n2) e2.output[n2] = String(t3.output[n2]);
              }
              if (null != t3.name && (e2.name = String(t3.name)), null != t3.opType && (e2.opType = String(t3.opType)), null != t3.domain && (e2.domain = String(t3.domain)), t3.attribute) {
                if (!Array.isArray(t3.attribute)) throw TypeError(".onnx.NodeProto.attribute: array expected");
                for (e2.attribute = [], n2 = 0; n2 < t3.attribute.length; ++n2) {
                  if ("object" != typeof t3.attribute[n2]) throw TypeError(".onnx.NodeProto.attribute: object expected");
                  e2.attribute[n2] = l.onnx.AttributeProto.fromObject(t3.attribute[n2]);
                }
              }
              return null != t3.docString && (e2.docString = String(t3.docString)), e2;
            }, t2.toObject = function(t3, e2) {
              e2 || (e2 = {});
              var n2 = {};
              if ((e2.arrays || e2.defaults) && (n2.input = [], n2.output = [], n2.attribute = []), e2.defaults && (n2.name = "", n2.opType = "", n2.docString = "", n2.domain = ""), t3.input && t3.input.length) {
                n2.input = [];
                for (var r2 = 0; r2 < t3.input.length; ++r2) n2.input[r2] = t3.input[r2];
              }
              if (t3.output && t3.output.length) for (n2.output = [], r2 = 0; r2 < t3.output.length; ++r2) n2.output[r2] = t3.output[r2];
              if (null != t3.name && t3.hasOwnProperty("name") && (n2.name = t3.name), null != t3.opType && t3.hasOwnProperty("opType") && (n2.opType = t3.opType), t3.attribute && t3.attribute.length) for (n2.attribute = [], r2 = 0; r2 < t3.attribute.length; ++r2) n2.attribute[r2] = l.onnx.AttributeProto.toObject(t3.attribute[r2], e2);
              return null != t3.docString && t3.hasOwnProperty("docString") && (n2.docString = t3.docString), null != t3.domain && t3.hasOwnProperty("domain") && (n2.domain = t3.domain), n2;
            }, t2.prototype.toJSON = function() {
              return this.constructor.toObject(this, a.util.toJSONOptions);
            }, t2;
          })(), o.ModelProto = (function() {
            function t2(t3) {
              if (this.opsetImport = [], this.metadataProps = [], t3) for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2) null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]);
            }
            return t2.prototype.irVersion = c.Long ? c.Long.fromBits(0, 0, false) : 0, t2.prototype.opsetImport = c.emptyArray, t2.prototype.producerName = "", t2.prototype.producerVersion = "", t2.prototype.domain = "", t2.prototype.modelVersion = c.Long ? c.Long.fromBits(0, 0, false) : 0, t2.prototype.docString = "", t2.prototype.graph = null, t2.prototype.metadataProps = c.emptyArray, t2.create = function(e2) {
              return new t2(e2);
            }, t2.encode = function(t3, e2) {
              if (e2 || (e2 = u.create()), null != t3.irVersion && t3.hasOwnProperty("irVersion") && e2.uint32(8).int64(t3.irVersion), null != t3.producerName && t3.hasOwnProperty("producerName") && e2.uint32(18).string(t3.producerName), null != t3.producerVersion && t3.hasOwnProperty("producerVersion") && e2.uint32(26).string(t3.producerVersion), null != t3.domain && t3.hasOwnProperty("domain") && e2.uint32(34).string(t3.domain), null != t3.modelVersion && t3.hasOwnProperty("modelVersion") && e2.uint32(40).int64(t3.modelVersion), null != t3.docString && t3.hasOwnProperty("docString") && e2.uint32(50).string(t3.docString), null != t3.graph && t3.hasOwnProperty("graph") && l.onnx.GraphProto.encode(t3.graph, e2.uint32(58).fork()).ldelim(), null != t3.opsetImport && t3.opsetImport.length) for (var n2 = 0; n2 < t3.opsetImport.length; ++n2) l.onnx.OperatorSetIdProto.encode(t3.opsetImport[n2], e2.uint32(66).fork()).ldelim();
              if (null != t3.metadataProps && t3.metadataProps.length) for (n2 = 0; n2 < t3.metadataProps.length; ++n2) l.onnx.StringStringEntryProto.encode(t3.metadataProps[n2], e2.uint32(114).fork()).ldelim();
              return e2;
            }, t2.encodeDelimited = function(t3, e2) {
              return this.encode(t3, e2).ldelim();
            }, t2.decode = function(t3, e2) {
              t3 instanceof s || (t3 = s.create(t3));
              for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.ModelProto(); t3.pos < n2; ) {
                var i3 = t3.uint32();
                switch (i3 >>> 3) {
                  case 1:
                    r2.irVersion = t3.int64();
                    break;
                  case 8:
                    r2.opsetImport && r2.opsetImport.length || (r2.opsetImport = []), r2.opsetImport.push(l.onnx.OperatorSetIdProto.decode(t3, t3.uint32()));
                    break;
                  case 2:
                    r2.producerName = t3.string();
                    break;
                  case 3:
                    r2.producerVersion = t3.string();
                    break;
                  case 4:
                    r2.domain = t3.string();
                    break;
                  case 5:
                    r2.modelVersion = t3.int64();
                    break;
                  case 6:
                    r2.docString = t3.string();
                    break;
                  case 7:
                    r2.graph = l.onnx.GraphProto.decode(t3, t3.uint32());
                    break;
                  case 14:
                    r2.metadataProps && r2.metadataProps.length || (r2.metadataProps = []), r2.metadataProps.push(l.onnx.StringStringEntryProto.decode(t3, t3.uint32()));
                    break;
                  default:
                    t3.skipType(7 & i3);
                }
              }
              return r2;
            }, t2.decodeDelimited = function(t3) {
              return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32());
            }, t2.verify = function(t3) {
              if ("object" != typeof t3 || null === t3) return "object expected";
              if (null != t3.irVersion && t3.hasOwnProperty("irVersion") && !(c.isInteger(t3.irVersion) || t3.irVersion && c.isInteger(t3.irVersion.low) && c.isInteger(t3.irVersion.high))) return "irVersion: integer|Long expected";
              if (null != t3.opsetImport && t3.hasOwnProperty("opsetImport")) {
                if (!Array.isArray(t3.opsetImport)) return "opsetImport: array expected";
                for (var e2 = 0; e2 < t3.opsetImport.length; ++e2) if (n2 = l.onnx.OperatorSetIdProto.verify(t3.opsetImport[e2])) return "opsetImport." + n2;
              }
              if (null != t3.producerName && t3.hasOwnProperty("producerName") && !c.isString(t3.producerName)) return "producerName: string expected";
              if (null != t3.producerVersion && t3.hasOwnProperty("producerVersion") && !c.isString(t3.producerVersion)) return "producerVersion: string expected";
              if (null != t3.domain && t3.hasOwnProperty("domain") && !c.isString(t3.domain)) return "domain: string expected";
              if (null != t3.modelVersion && t3.hasOwnProperty("modelVersion") && !(c.isInteger(t3.modelVersion) || t3.modelVersion && c.isInteger(t3.modelVersion.low) && c.isInteger(t3.modelVersion.high))) return "modelVersion: integer|Long expected";
              if (null != t3.docString && t3.hasOwnProperty("docString") && !c.isString(t3.docString)) return "docString: string expected";
              if (null != t3.graph && t3.hasOwnProperty("graph") && (n2 = l.onnx.GraphProto.verify(t3.graph))) return "graph." + n2;
              if (null != t3.metadataProps && t3.hasOwnProperty("metadataProps")) {
                if (!Array.isArray(t3.metadataProps)) return "metadataProps: array expected";
                for (e2 = 0; e2 < t3.metadataProps.length; ++e2) {
                  var n2;
                  if (n2 = l.onnx.StringStringEntryProto.verify(t3.metadataProps[e2])) return "metadataProps." + n2;
                }
              }
              return null;
            }, t2.fromObject = function(t3) {
              if (t3 instanceof l.onnx.ModelProto) return t3;
              var e2 = new l.onnx.ModelProto();
              if (null != t3.irVersion && (c.Long ? (e2.irVersion = c.Long.fromValue(t3.irVersion)).unsigned = false : "string" == typeof t3.irVersion ? e2.irVersion = parseInt(t3.irVersion, 10) : "number" == typeof t3.irVersion ? e2.irVersion = t3.irVersion : "object" == typeof t3.irVersion && (e2.irVersion = new c.LongBits(t3.irVersion.low >>> 0, t3.irVersion.high >>> 0).toNumber())), t3.opsetImport) {
                if (!Array.isArray(t3.opsetImport)) throw TypeError(".onnx.ModelProto.opsetImport: array expected");
                e2.opsetImport = [];
                for (var n2 = 0; n2 < t3.opsetImport.length; ++n2) {
                  if ("object" != typeof t3.opsetImport[n2]) throw TypeError(".onnx.ModelProto.opsetImport: object expected");
                  e2.opsetImport[n2] = l.onnx.OperatorSetIdProto.fromObject(t3.opsetImport[n2]);
                }
              }
              if (null != t3.producerName && (e2.producerName = String(t3.producerName)), null != t3.producerVersion && (e2.producerVersion = String(t3.producerVersion)), null != t3.domain && (e2.domain = String(t3.domain)), null != t3.modelVersion && (c.Long ? (e2.modelVersion = c.Long.fromValue(t3.modelVersion)).unsigned = false : "string" == typeof t3.modelVersion ? e2.modelVersion = parseInt(t3.modelVersion, 10) : "number" == typeof t3.modelVersion ? e2.modelVersion = t3.modelVersion : "object" == typeof t3.modelVersion && (e2.modelVersion = new c.LongBits(t3.modelVersion.low >>> 0, t3.modelVersion.high >>> 0).toNumber())), null != t3.docString && (e2.docString = String(t3.docString)), null != t3.graph) {
                if ("object" != typeof t3.graph) throw TypeError(".onnx.ModelProto.graph: object expected");
                e2.graph = l.onnx.GraphProto.fromObject(t3.graph);
              }
              if (t3.metadataProps) {
                if (!Array.isArray(t3.metadataProps)) throw TypeError(".onnx.ModelProto.metadataProps: array expected");
                for (e2.metadataProps = [], n2 = 0; n2 < t3.metadataProps.length; ++n2) {
                  if ("object" != typeof t3.metadataProps[n2]) throw TypeError(".onnx.ModelProto.metadataProps: object expected");
                  e2.metadataProps[n2] = l.onnx.StringStringEntryProto.fromObject(t3.metadataProps[n2]);
                }
              }
              return e2;
            }, t2.toObject = function(t3, e2) {
              e2 || (e2 = {});
              var n2 = {};
              if ((e2.arrays || e2.defaults) && (n2.opsetImport = [], n2.metadataProps = []), e2.defaults) {
                if (c.Long) {
                  var r2 = new c.Long(0, 0, false);
                  n2.irVersion = e2.longs === String ? r2.toString() : e2.longs === Number ? r2.toNumber() : r2;
                } else n2.irVersion = e2.longs === String ? "0" : 0;
                n2.producerName = "", n2.producerVersion = "", n2.domain = "", c.Long ? (r2 = new c.Long(0, 0, false), n2.modelVersion = e2.longs === String ? r2.toString() : e2.longs === Number ? r2.toNumber() : r2) : n2.modelVersion = e2.longs === String ? "0" : 0, n2.docString = "", n2.graph = null;
              }
              if (null != t3.irVersion && t3.hasOwnProperty("irVersion") && ("number" == typeof t3.irVersion ? n2.irVersion = e2.longs === String ? String(t3.irVersion) : t3.irVersion : n2.irVersion = e2.longs === String ? c.Long.prototype.toString.call(t3.irVersion) : e2.longs === Number ? new c.LongBits(t3.irVersion.low >>> 0, t3.irVersion.high >>> 0).toNumber() : t3.irVersion), null != t3.producerName && t3.hasOwnProperty("producerName") && (n2.producerName = t3.producerName), null != t3.producerVersion && t3.hasOwnProperty("producerVersion") && (n2.producerVersion = t3.producerVersion), null != t3.domain && t3.hasOwnProperty("domain") && (n2.domain = t3.domain), null != t3.modelVersion && t3.hasOwnProperty("modelVersion") && ("number" == typeof t3.modelVersion ? n2.modelVersion = e2.longs === String ? String(t3.modelVersion) : t3.modelVersion : n2.modelVersion = e2.longs === String ? c.Long.prototype.toString.call(t3.modelVersion) : e2.longs === Number ? new c.LongBits(t3.modelVersion.low >>> 0, t3.modelVersion.high >>> 0).toNumber() : t3.modelVersion), null != t3.docString && t3.hasOwnProperty("docString") && (n2.docString = t3.docString), null != t3.graph && t3.hasOwnProperty("graph") && (n2.graph = l.onnx.GraphProto.toObject(t3.graph, e2)), t3.opsetImport && t3.opsetImport.length) {
                n2.opsetImport = [];
                for (var i3 = 0; i3 < t3.opsetImport.length; ++i3) n2.opsetImport[i3] = l.onnx.OperatorSetIdProto.toObject(t3.opsetImport[i3], e2);
              }
              if (t3.metadataProps && t3.metadataProps.length) for (n2.metadataProps = [], i3 = 0; i3 < t3.metadataProps.length; ++i3) n2.metadataProps[i3] = l.onnx.StringStringEntryProto.toObject(t3.metadataProps[i3], e2);
              return n2;
            }, t2.prototype.toJSON = function() {
              return this.constructor.toObject(this, a.util.toJSONOptions);
            }, t2;
          })(), o.StringStringEntryProto = (function() {
            function t2(t3) {
              if (t3) for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2) null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]);
            }
            return t2.prototype.key = "", t2.prototype.value = "", t2.create = function(e2) {
              return new t2(e2);
            }, t2.encode = function(t3, e2) {
              return e2 || (e2 = u.create()), null != t3.key && t3.hasOwnProperty("key") && e2.uint32(10).string(t3.key), null != t3.value && t3.hasOwnProperty("value") && e2.uint32(18).string(t3.value), e2;
            }, t2.encodeDelimited = function(t3, e2) {
              return this.encode(t3, e2).ldelim();
            }, t2.decode = function(t3, e2) {
              t3 instanceof s || (t3 = s.create(t3));
              for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.StringStringEntryProto(); t3.pos < n2; ) {
                var i3 = t3.uint32();
                switch (i3 >>> 3) {
                  case 1:
                    r2.key = t3.string();
                    break;
                  case 2:
                    r2.value = t3.string();
                    break;
                  default:
                    t3.skipType(7 & i3);
                }
              }
              return r2;
            }, t2.decodeDelimited = function(t3) {
              return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32());
            }, t2.verify = function(t3) {
              return "object" != typeof t3 || null === t3 ? "object expected" : null != t3.key && t3.hasOwnProperty("key") && !c.isString(t3.key) ? "key: string expected" : null != t3.value && t3.hasOwnProperty("value") && !c.isString(t3.value) ? "value: string expected" : null;
            }, t2.fromObject = function(t3) {
              if (t3 instanceof l.onnx.StringStringEntryProto) return t3;
              var e2 = new l.onnx.StringStringEntryProto();
              return null != t3.key && (e2.key = String(t3.key)), null != t3.value && (e2.value = String(t3.value)), e2;
            }, t2.toObject = function(t3, e2) {
              e2 || (e2 = {});
              var n2 = {};
              return e2.defaults && (n2.key = "", n2.value = ""), null != t3.key && t3.hasOwnProperty("key") && (n2.key = t3.key), null != t3.value && t3.hasOwnProperty("value") && (n2.value = t3.value), n2;
            }, t2.prototype.toJSON = function() {
              return this.constructor.toObject(this, a.util.toJSONOptions);
            }, t2;
          })(), o.TensorAnnotation = (function() {
            function t2(t3) {
              if (this.quantParameterTensorNames = [], t3) for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2) null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]);
            }
            return t2.prototype.tensorName = "", t2.prototype.quantParameterTensorNames = c.emptyArray, t2.create = function(e2) {
              return new t2(e2);
            }, t2.encode = function(t3, e2) {
              if (e2 || (e2 = u.create()), null != t3.tensorName && t3.hasOwnProperty("tensorName") && e2.uint32(10).string(t3.tensorName), null != t3.quantParameterTensorNames && t3.quantParameterTensorNames.length) for (var n2 = 0; n2 < t3.quantParameterTensorNames.length; ++n2) l.onnx.StringStringEntryProto.encode(t3.quantParameterTensorNames[n2], e2.uint32(18).fork()).ldelim();
              return e2;
            }, t2.encodeDelimited = function(t3, e2) {
              return this.encode(t3, e2).ldelim();
            }, t2.decode = function(t3, e2) {
              t3 instanceof s || (t3 = s.create(t3));
              for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.TensorAnnotation(); t3.pos < n2; ) {
                var i3 = t3.uint32();
                switch (i3 >>> 3) {
                  case 1:
                    r2.tensorName = t3.string();
                    break;
                  case 2:
                    r2.quantParameterTensorNames && r2.quantParameterTensorNames.length || (r2.quantParameterTensorNames = []), r2.quantParameterTensorNames.push(l.onnx.StringStringEntryProto.decode(t3, t3.uint32()));
                    break;
                  default:
                    t3.skipType(7 & i3);
                }
              }
              return r2;
            }, t2.decodeDelimited = function(t3) {
              return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32());
            }, t2.verify = function(t3) {
              if ("object" != typeof t3 || null === t3) return "object expected";
              if (null != t3.tensorName && t3.hasOwnProperty("tensorName") && !c.isString(t3.tensorName)) return "tensorName: string expected";
              if (null != t3.quantParameterTensorNames && t3.hasOwnProperty("quantParameterTensorNames")) {
                if (!Array.isArray(t3.quantParameterTensorNames)) return "quantParameterTensorNames: array expected";
                for (var e2 = 0; e2 < t3.quantParameterTensorNames.length; ++e2) {
                  var n2 = l.onnx.StringStringEntryProto.verify(t3.quantParameterTensorNames[e2]);
                  if (n2) return "quantParameterTensorNames." + n2;
                }
              }
              return null;
            }, t2.fromObject = function(t3) {
              if (t3 instanceof l.onnx.TensorAnnotation) return t3;
              var e2 = new l.onnx.TensorAnnotation();
              if (null != t3.tensorName && (e2.tensorName = String(t3.tensorName)), t3.quantParameterTensorNames) {
                if (!Array.isArray(t3.quantParameterTensorNames)) throw TypeError(".onnx.TensorAnnotation.quantParameterTensorNames: array expected");
                e2.quantParameterTensorNames = [];
                for (var n2 = 0; n2 < t3.quantParameterTensorNames.length; ++n2) {
                  if ("object" != typeof t3.quantParameterTensorNames[n2]) throw TypeError(".onnx.TensorAnnotation.quantParameterTensorNames: object expected");
                  e2.quantParameterTensorNames[n2] = l.onnx.StringStringEntryProto.fromObject(t3.quantParameterTensorNames[n2]);
                }
              }
              return e2;
            }, t2.toObject = function(t3, e2) {
              e2 || (e2 = {});
              var n2 = {};
              if ((e2.arrays || e2.defaults) && (n2.quantParameterTensorNames = []), e2.defaults && (n2.tensorName = ""), null != t3.tensorName && t3.hasOwnProperty("tensorName") && (n2.tensorName = t3.tensorName), t3.quantParameterTensorNames && t3.quantParameterTensorNames.length) {
                n2.quantParameterTensorNames = [];
                for (var r2 = 0; r2 < t3.quantParameterTensorNames.length; ++r2) n2.quantParameterTensorNames[r2] = l.onnx.StringStringEntryProto.toObject(t3.quantParameterTensorNames[r2], e2);
              }
              return n2;
            }, t2.prototype.toJSON = function() {
              return this.constructor.toObject(this, a.util.toJSONOptions);
            }, t2;
          })(), o.GraphProto = (function() {
            function t2(t3) {
              if (this.node = [], this.initializer = [], this.input = [], this.output = [], this.valueInfo = [], this.quantizationAnnotation = [], t3) for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2) null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]);
            }
            return t2.prototype.node = c.emptyArray, t2.prototype.name = "", t2.prototype.initializer = c.emptyArray, t2.prototype.docString = "", t2.prototype.input = c.emptyArray, t2.prototype.output = c.emptyArray, t2.prototype.valueInfo = c.emptyArray, t2.prototype.quantizationAnnotation = c.emptyArray, t2.create = function(e2) {
              return new t2(e2);
            }, t2.encode = function(t3, e2) {
              if (e2 || (e2 = u.create()), null != t3.node && t3.node.length) for (var n2 = 0; n2 < t3.node.length; ++n2) l.onnx.NodeProto.encode(t3.node[n2], e2.uint32(10).fork()).ldelim();
              if (null != t3.name && t3.hasOwnProperty("name") && e2.uint32(18).string(t3.name), null != t3.initializer && t3.initializer.length) for (n2 = 0; n2 < t3.initializer.length; ++n2) l.onnx.TensorProto.encode(t3.initializer[n2], e2.uint32(42).fork()).ldelim();
              if (null != t3.docString && t3.hasOwnProperty("docString") && e2.uint32(82).string(t3.docString), null != t3.input && t3.input.length) for (n2 = 0; n2 < t3.input.length; ++n2) l.onnx.ValueInfoProto.encode(t3.input[n2], e2.uint32(90).fork()).ldelim();
              if (null != t3.output && t3.output.length) for (n2 = 0; n2 < t3.output.length; ++n2) l.onnx.ValueInfoProto.encode(t3.output[n2], e2.uint32(98).fork()).ldelim();
              if (null != t3.valueInfo && t3.valueInfo.length) for (n2 = 0; n2 < t3.valueInfo.length; ++n2) l.onnx.ValueInfoProto.encode(t3.valueInfo[n2], e2.uint32(106).fork()).ldelim();
              if (null != t3.quantizationAnnotation && t3.quantizationAnnotation.length) for (n2 = 0; n2 < t3.quantizationAnnotation.length; ++n2) l.onnx.TensorAnnotation.encode(t3.quantizationAnnotation[n2], e2.uint32(114).fork()).ldelim();
              return e2;
            }, t2.encodeDelimited = function(t3, e2) {
              return this.encode(t3, e2).ldelim();
            }, t2.decode = function(t3, e2) {
              t3 instanceof s || (t3 = s.create(t3));
              for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.GraphProto(); t3.pos < n2; ) {
                var i3 = t3.uint32();
                switch (i3 >>> 3) {
                  case 1:
                    r2.node && r2.node.length || (r2.node = []), r2.node.push(l.onnx.NodeProto.decode(t3, t3.uint32()));
                    break;
                  case 2:
                    r2.name = t3.string();
                    break;
                  case 5:
                    r2.initializer && r2.initializer.length || (r2.initializer = []), r2.initializer.push(l.onnx.TensorProto.decode(t3, t3.uint32()));
                    break;
                  case 10:
                    r2.docString = t3.string();
                    break;
                  case 11:
                    r2.input && r2.input.length || (r2.input = []), r2.input.push(l.onnx.ValueInfoProto.decode(t3, t3.uint32()));
                    break;
                  case 12:
                    r2.output && r2.output.length || (r2.output = []), r2.output.push(l.onnx.ValueInfoProto.decode(t3, t3.uint32()));
                    break;
                  case 13:
                    r2.valueInfo && r2.valueInfo.length || (r2.valueInfo = []), r2.valueInfo.push(l.onnx.ValueInfoProto.decode(t3, t3.uint32()));
                    break;
                  case 14:
                    r2.quantizationAnnotation && r2.quantizationAnnotation.length || (r2.quantizationAnnotation = []), r2.quantizationAnnotation.push(l.onnx.TensorAnnotation.decode(t3, t3.uint32()));
                    break;
                  default:
                    t3.skipType(7 & i3);
                }
              }
              return r2;
            }, t2.decodeDelimited = function(t3) {
              return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32());
            }, t2.verify = function(t3) {
              if ("object" != typeof t3 || null === t3) return "object expected";
              if (null != t3.node && t3.hasOwnProperty("node")) {
                if (!Array.isArray(t3.node)) return "node: array expected";
                for (var e2 = 0; e2 < t3.node.length; ++e2) if (n2 = l.onnx.NodeProto.verify(t3.node[e2])) return "node." + n2;
              }
              if (null != t3.name && t3.hasOwnProperty("name") && !c.isString(t3.name)) return "name: string expected";
              if (null != t3.initializer && t3.hasOwnProperty("initializer")) {
                if (!Array.isArray(t3.initializer)) return "initializer: array expected";
                for (e2 = 0; e2 < t3.initializer.length; ++e2) if (n2 = l.onnx.TensorProto.verify(t3.initializer[e2])) return "initializer." + n2;
              }
              if (null != t3.docString && t3.hasOwnProperty("docString") && !c.isString(t3.docString)) return "docString: string expected";
              if (null != t3.input && t3.hasOwnProperty("input")) {
                if (!Array.isArray(t3.input)) return "input: array expected";
                for (e2 = 0; e2 < t3.input.length; ++e2) if (n2 = l.onnx.ValueInfoProto.verify(t3.input[e2])) return "input." + n2;
              }
              if (null != t3.output && t3.hasOwnProperty("output")) {
                if (!Array.isArray(t3.output)) return "output: array expected";
                for (e2 = 0; e2 < t3.output.length; ++e2) if (n2 = l.onnx.ValueInfoProto.verify(t3.output[e2])) return "output." + n2;
              }
              if (null != t3.valueInfo && t3.hasOwnProperty("valueInfo")) {
                if (!Array.isArray(t3.valueInfo)) return "valueInfo: array expected";
                for (e2 = 0; e2 < t3.valueInfo.length; ++e2) if (n2 = l.onnx.ValueInfoProto.verify(t3.valueInfo[e2])) return "valueInfo." + n2;
              }
              if (null != t3.quantizationAnnotation && t3.hasOwnProperty("quantizationAnnotation")) {
                if (!Array.isArray(t3.quantizationAnnotation)) return "quantizationAnnotation: array expected";
                for (e2 = 0; e2 < t3.quantizationAnnotation.length; ++e2) {
                  var n2;
                  if (n2 = l.onnx.TensorAnnotation.verify(t3.quantizationAnnotation[e2])) return "quantizationAnnotation." + n2;
                }
              }
              return null;
            }, t2.fromObject = function(t3) {
              if (t3 instanceof l.onnx.GraphProto) return t3;
              var e2 = new l.onnx.GraphProto();
              if (t3.node) {
                if (!Array.isArray(t3.node)) throw TypeError(".onnx.GraphProto.node: array expected");
                e2.node = [];
                for (var n2 = 0; n2 < t3.node.length; ++n2) {
                  if ("object" != typeof t3.node[n2]) throw TypeError(".onnx.GraphProto.node: object expected");
                  e2.node[n2] = l.onnx.NodeProto.fromObject(t3.node[n2]);
                }
              }
              if (null != t3.name && (e2.name = String(t3.name)), t3.initializer) {
                if (!Array.isArray(t3.initializer)) throw TypeError(".onnx.GraphProto.initializer: array expected");
                for (e2.initializer = [], n2 = 0; n2 < t3.initializer.length; ++n2) {
                  if ("object" != typeof t3.initializer[n2]) throw TypeError(".onnx.GraphProto.initializer: object expected");
                  e2.initializer[n2] = l.onnx.TensorProto.fromObject(t3.initializer[n2]);
                }
              }
              if (null != t3.docString && (e2.docString = String(t3.docString)), t3.input) {
                if (!Array.isArray(t3.input)) throw TypeError(".onnx.GraphProto.input: array expected");
                for (e2.input = [], n2 = 0; n2 < t3.input.length; ++n2) {
                  if ("object" != typeof t3.input[n2]) throw TypeError(".onnx.GraphProto.input: object expected");
                  e2.input[n2] = l.onnx.ValueInfoProto.fromObject(t3.input[n2]);
                }
              }
              if (t3.output) {
                if (!Array.isArray(t3.output)) throw TypeError(".onnx.GraphProto.output: array expected");
                for (e2.output = [], n2 = 0; n2 < t3.output.length; ++n2) {
                  if ("object" != typeof t3.output[n2]) throw TypeError(".onnx.GraphProto.output: object expected");
                  e2.output[n2] = l.onnx.ValueInfoProto.fromObject(t3.output[n2]);
                }
              }
              if (t3.valueInfo) {
                if (!Array.isArray(t3.valueInfo)) throw TypeError(".onnx.GraphProto.valueInfo: array expected");
                for (e2.valueInfo = [], n2 = 0; n2 < t3.valueInfo.length; ++n2) {
                  if ("object" != typeof t3.valueInfo[n2]) throw TypeError(".onnx.GraphProto.valueInfo: object expected");
                  e2.valueInfo[n2] = l.onnx.ValueInfoProto.fromObject(t3.valueInfo[n2]);
                }
              }
              if (t3.quantizationAnnotation) {
                if (!Array.isArray(t3.quantizationAnnotation)) throw TypeError(".onnx.GraphProto.quantizationAnnotation: array expected");
                for (e2.quantizationAnnotation = [], n2 = 0; n2 < t3.quantizationAnnotation.length; ++n2) {
                  if ("object" != typeof t3.quantizationAnnotation[n2]) throw TypeError(".onnx.GraphProto.quantizationAnnotation: object expected");
                  e2.quantizationAnnotation[n2] = l.onnx.TensorAnnotation.fromObject(t3.quantizationAnnotation[n2]);
                }
              }
              return e2;
            }, t2.toObject = function(t3, e2) {
              e2 || (e2 = {});
              var n2 = {};
              if ((e2.arrays || e2.defaults) && (n2.node = [], n2.initializer = [], n2.input = [], n2.output = [], n2.valueInfo = [], n2.quantizationAnnotation = []), e2.defaults && (n2.name = "", n2.docString = ""), t3.node && t3.node.length) {
                n2.node = [];
                for (var r2 = 0; r2 < t3.node.length; ++r2) n2.node[r2] = l.onnx.NodeProto.toObject(t3.node[r2], e2);
              }
              if (null != t3.name && t3.hasOwnProperty("name") && (n2.name = t3.name), t3.initializer && t3.initializer.length) for (n2.initializer = [], r2 = 0; r2 < t3.initializer.length; ++r2) n2.initializer[r2] = l.onnx.TensorProto.toObject(t3.initializer[r2], e2);
              if (null != t3.docString && t3.hasOwnProperty("docString") && (n2.docString = t3.docString), t3.input && t3.input.length) for (n2.input = [], r2 = 0; r2 < t3.input.length; ++r2) n2.input[r2] = l.onnx.ValueInfoProto.toObject(t3.input[r2], e2);
              if (t3.output && t3.output.length) for (n2.output = [], r2 = 0; r2 < t3.output.length; ++r2) n2.output[r2] = l.onnx.ValueInfoProto.toObject(t3.output[r2], e2);
              if (t3.valueInfo && t3.valueInfo.length) for (n2.valueInfo = [], r2 = 0; r2 < t3.valueInfo.length; ++r2) n2.valueInfo[r2] = l.onnx.ValueInfoProto.toObject(t3.valueInfo[r2], e2);
              if (t3.quantizationAnnotation && t3.quantizationAnnotation.length) for (n2.quantizationAnnotation = [], r2 = 0; r2 < t3.quantizationAnnotation.length; ++r2) n2.quantizationAnnotation[r2] = l.onnx.TensorAnnotation.toObject(t3.quantizationAnnotation[r2], e2);
              return n2;
            }, t2.prototype.toJSON = function() {
              return this.constructor.toObject(this, a.util.toJSONOptions);
            }, t2;
          })(), o.TensorProto = (function() {
            function t2(t3) {
              if (this.dims = [], this.floatData = [], this.int32Data = [], this.stringData = [], this.int64Data = [], this.externalData = [], this.doubleData = [], this.uint64Data = [], t3) for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2) null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]);
            }
            return t2.prototype.dims = c.emptyArray, t2.prototype.dataType = 0, t2.prototype.segment = null, t2.prototype.floatData = c.emptyArray, t2.prototype.int32Data = c.emptyArray, t2.prototype.stringData = c.emptyArray, t2.prototype.int64Data = c.emptyArray, t2.prototype.name = "", t2.prototype.docString = "", t2.prototype.rawData = c.newBuffer([]), t2.prototype.externalData = c.emptyArray, t2.prototype.dataLocation = 0, t2.prototype.doubleData = c.emptyArray, t2.prototype.uint64Data = c.emptyArray, t2.create = function(e2) {
              return new t2(e2);
            }, t2.encode = function(t3, e2) {
              if (e2 || (e2 = u.create()), null != t3.dims && t3.dims.length) {
                e2.uint32(10).fork();
                for (var n2 = 0; n2 < t3.dims.length; ++n2) e2.int64(t3.dims[n2]);
                e2.ldelim();
              }
              if (null != t3.dataType && t3.hasOwnProperty("dataType") && e2.uint32(16).int32(t3.dataType), null != t3.segment && t3.hasOwnProperty("segment") && l.onnx.TensorProto.Segment.encode(t3.segment, e2.uint32(26).fork()).ldelim(), null != t3.floatData && t3.floatData.length) {
                for (e2.uint32(34).fork(), n2 = 0; n2 < t3.floatData.length; ++n2) e2.float(t3.floatData[n2]);
                e2.ldelim();
              }
              if (null != t3.int32Data && t3.int32Data.length) {
                for (e2.uint32(42).fork(), n2 = 0; n2 < t3.int32Data.length; ++n2) e2.int32(t3.int32Data[n2]);
                e2.ldelim();
              }
              if (null != t3.stringData && t3.stringData.length) for (n2 = 0; n2 < t3.stringData.length; ++n2) e2.uint32(50).bytes(t3.stringData[n2]);
              if (null != t3.int64Data && t3.int64Data.length) {
                for (e2.uint32(58).fork(), n2 = 0; n2 < t3.int64Data.length; ++n2) e2.int64(t3.int64Data[n2]);
                e2.ldelim();
              }
              if (null != t3.name && t3.hasOwnProperty("name") && e2.uint32(66).string(t3.name), null != t3.rawData && t3.hasOwnProperty("rawData") && e2.uint32(74).bytes(t3.rawData), null != t3.doubleData && t3.doubleData.length) {
                for (e2.uint32(82).fork(), n2 = 0; n2 < t3.doubleData.length; ++n2) e2.double(t3.doubleData[n2]);
                e2.ldelim();
              }
              if (null != t3.uint64Data && t3.uint64Data.length) {
                for (e2.uint32(90).fork(), n2 = 0; n2 < t3.uint64Data.length; ++n2) e2.uint64(t3.uint64Data[n2]);
                e2.ldelim();
              }
              if (null != t3.docString && t3.hasOwnProperty("docString") && e2.uint32(98).string(t3.docString), null != t3.externalData && t3.externalData.length) for (n2 = 0; n2 < t3.externalData.length; ++n2) l.onnx.StringStringEntryProto.encode(t3.externalData[n2], e2.uint32(106).fork()).ldelim();
              return null != t3.dataLocation && t3.hasOwnProperty("dataLocation") && e2.uint32(112).int32(t3.dataLocation), e2;
            }, t2.encodeDelimited = function(t3, e2) {
              return this.encode(t3, e2).ldelim();
            }, t2.decode = function(t3, e2) {
              t3 instanceof s || (t3 = s.create(t3));
              for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.TensorProto(); t3.pos < n2; ) {
                var i3 = t3.uint32();
                switch (i3 >>> 3) {
                  case 1:
                    if (r2.dims && r2.dims.length || (r2.dims = []), 2 == (7 & i3)) for (var o2 = t3.uint32() + t3.pos; t3.pos < o2; ) r2.dims.push(t3.int64());
                    else r2.dims.push(t3.int64());
                    break;
                  case 2:
                    r2.dataType = t3.int32();
                    break;
                  case 3:
                    r2.segment = l.onnx.TensorProto.Segment.decode(t3, t3.uint32());
                    break;
                  case 4:
                    if (r2.floatData && r2.floatData.length || (r2.floatData = []), 2 == (7 & i3)) for (o2 = t3.uint32() + t3.pos; t3.pos < o2; ) r2.floatData.push(t3.float());
                    else r2.floatData.push(t3.float());
                    break;
                  case 5:
                    if (r2.int32Data && r2.int32Data.length || (r2.int32Data = []), 2 == (7 & i3)) for (o2 = t3.uint32() + t3.pos; t3.pos < o2; ) r2.int32Data.push(t3.int32());
                    else r2.int32Data.push(t3.int32());
                    break;
                  case 6:
                    r2.stringData && r2.stringData.length || (r2.stringData = []), r2.stringData.push(t3.bytes());
                    break;
                  case 7:
                    if (r2.int64Data && r2.int64Data.length || (r2.int64Data = []), 2 == (7 & i3)) for (o2 = t3.uint32() + t3.pos; t3.pos < o2; ) r2.int64Data.push(t3.int64());
                    else r2.int64Data.push(t3.int64());
                    break;
                  case 8:
                    r2.name = t3.string();
                    break;
                  case 12:
                    r2.docString = t3.string();
                    break;
                  case 9:
                    r2.rawData = t3.bytes();
                    break;
                  case 13:
                    r2.externalData && r2.externalData.length || (r2.externalData = []), r2.externalData.push(l.onnx.StringStringEntryProto.decode(t3, t3.uint32()));
                    break;
                  case 14:
                    r2.dataLocation = t3.int32();
                    break;
                  case 10:
                    if (r2.doubleData && r2.doubleData.length || (r2.doubleData = []), 2 == (7 & i3)) for (o2 = t3.uint32() + t3.pos; t3.pos < o2; ) r2.doubleData.push(t3.double());
                    else r2.doubleData.push(t3.double());
                    break;
                  case 11:
                    if (r2.uint64Data && r2.uint64Data.length || (r2.uint64Data = []), 2 == (7 & i3)) for (o2 = t3.uint32() + t3.pos; t3.pos < o2; ) r2.uint64Data.push(t3.uint64());
                    else r2.uint64Data.push(t3.uint64());
                    break;
                  default:
                    t3.skipType(7 & i3);
                }
              }
              return r2;
            }, t2.decodeDelimited = function(t3) {
              return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32());
            }, t2.verify = function(t3) {
              if ("object" != typeof t3 || null === t3) return "object expected";
              if (null != t3.dims && t3.hasOwnProperty("dims")) {
                if (!Array.isArray(t3.dims)) return "dims: array expected";
                for (var e2 = 0; e2 < t3.dims.length; ++e2) if (!(c.isInteger(t3.dims[e2]) || t3.dims[e2] && c.isInteger(t3.dims[e2].low) && c.isInteger(t3.dims[e2].high))) return "dims: integer|Long[] expected";
              }
              if (null != t3.dataType && t3.hasOwnProperty("dataType") && !c.isInteger(t3.dataType)) return "dataType: integer expected";
              if (null != t3.segment && t3.hasOwnProperty("segment") && (n2 = l.onnx.TensorProto.Segment.verify(t3.segment))) return "segment." + n2;
              if (null != t3.floatData && t3.hasOwnProperty("floatData")) {
                if (!Array.isArray(t3.floatData)) return "floatData: array expected";
                for (e2 = 0; e2 < t3.floatData.length; ++e2) if ("number" != typeof t3.floatData[e2]) return "floatData: number[] expected";
              }
              if (null != t3.int32Data && t3.hasOwnProperty("int32Data")) {
                if (!Array.isArray(t3.int32Data)) return "int32Data: array expected";
                for (e2 = 0; e2 < t3.int32Data.length; ++e2) if (!c.isInteger(t3.int32Data[e2])) return "int32Data: integer[] expected";
              }
              if (null != t3.stringData && t3.hasOwnProperty("stringData")) {
                if (!Array.isArray(t3.stringData)) return "stringData: array expected";
                for (e2 = 0; e2 < t3.stringData.length; ++e2) if (!(t3.stringData[e2] && "number" == typeof t3.stringData[e2].length || c.isString(t3.stringData[e2]))) return "stringData: buffer[] expected";
              }
              if (null != t3.int64Data && t3.hasOwnProperty("int64Data")) {
                if (!Array.isArray(t3.int64Data)) return "int64Data: array expected";
                for (e2 = 0; e2 < t3.int64Data.length; ++e2) if (!(c.isInteger(t3.int64Data[e2]) || t3.int64Data[e2] && c.isInteger(t3.int64Data[e2].low) && c.isInteger(t3.int64Data[e2].high))) return "int64Data: integer|Long[] expected";
              }
              if (null != t3.name && t3.hasOwnProperty("name") && !c.isString(t3.name)) return "name: string expected";
              if (null != t3.docString && t3.hasOwnProperty("docString") && !c.isString(t3.docString)) return "docString: string expected";
              if (null != t3.rawData && t3.hasOwnProperty("rawData") && !(t3.rawData && "number" == typeof t3.rawData.length || c.isString(t3.rawData))) return "rawData: buffer expected";
              if (null != t3.externalData && t3.hasOwnProperty("externalData")) {
                if (!Array.isArray(t3.externalData)) return "externalData: array expected";
                for (e2 = 0; e2 < t3.externalData.length; ++e2) {
                  var n2;
                  if (n2 = l.onnx.StringStringEntryProto.verify(t3.externalData[e2])) return "externalData." + n2;
                }
              }
              if (null != t3.dataLocation && t3.hasOwnProperty("dataLocation")) switch (t3.dataLocation) {
                default:
                  return "dataLocation: enum value expected";
                case 0:
                case 1:
              }
              if (null != t3.doubleData && t3.hasOwnProperty("doubleData")) {
                if (!Array.isArray(t3.doubleData)) return "doubleData: array expected";
                for (e2 = 0; e2 < t3.doubleData.length; ++e2) if ("number" != typeof t3.doubleData[e2]) return "doubleData: number[] expected";
              }
              if (null != t3.uint64Data && t3.hasOwnProperty("uint64Data")) {
                if (!Array.isArray(t3.uint64Data)) return "uint64Data: array expected";
                for (e2 = 0; e2 < t3.uint64Data.length; ++e2) if (!(c.isInteger(t3.uint64Data[e2]) || t3.uint64Data[e2] && c.isInteger(t3.uint64Data[e2].low) && c.isInteger(t3.uint64Data[e2].high))) return "uint64Data: integer|Long[] expected";
              }
              return null;
            }, t2.fromObject = function(t3) {
              if (t3 instanceof l.onnx.TensorProto) return t3;
              var e2 = new l.onnx.TensorProto();
              if (t3.dims) {
                if (!Array.isArray(t3.dims)) throw TypeError(".onnx.TensorProto.dims: array expected");
                e2.dims = [];
                for (var n2 = 0; n2 < t3.dims.length; ++n2) c.Long ? (e2.dims[n2] = c.Long.fromValue(t3.dims[n2])).unsigned = false : "string" == typeof t3.dims[n2] ? e2.dims[n2] = parseInt(t3.dims[n2], 10) : "number" == typeof t3.dims[n2] ? e2.dims[n2] = t3.dims[n2] : "object" == typeof t3.dims[n2] && (e2.dims[n2] = new c.LongBits(t3.dims[n2].low >>> 0, t3.dims[n2].high >>> 0).toNumber());
              }
              if (null != t3.dataType && (e2.dataType = 0 | t3.dataType), null != t3.segment) {
                if ("object" != typeof t3.segment) throw TypeError(".onnx.TensorProto.segment: object expected");
                e2.segment = l.onnx.TensorProto.Segment.fromObject(t3.segment);
              }
              if (t3.floatData) {
                if (!Array.isArray(t3.floatData)) throw TypeError(".onnx.TensorProto.floatData: array expected");
                for (e2.floatData = [], n2 = 0; n2 < t3.floatData.length; ++n2) e2.floatData[n2] = Number(t3.floatData[n2]);
              }
              if (t3.int32Data) {
                if (!Array.isArray(t3.int32Data)) throw TypeError(".onnx.TensorProto.int32Data: array expected");
                for (e2.int32Data = [], n2 = 0; n2 < t3.int32Data.length; ++n2) e2.int32Data[n2] = 0 | t3.int32Data[n2];
              }
              if (t3.stringData) {
                if (!Array.isArray(t3.stringData)) throw TypeError(".onnx.TensorProto.stringData: array expected");
                for (e2.stringData = [], n2 = 0; n2 < t3.stringData.length; ++n2) "string" == typeof t3.stringData[n2] ? c.base64.decode(t3.stringData[n2], e2.stringData[n2] = c.newBuffer(c.base64.length(t3.stringData[n2])), 0) : t3.stringData[n2].length && (e2.stringData[n2] = t3.stringData[n2]);
              }
              if (t3.int64Data) {
                if (!Array.isArray(t3.int64Data)) throw TypeError(".onnx.TensorProto.int64Data: array expected");
                for (e2.int64Data = [], n2 = 0; n2 < t3.int64Data.length; ++n2) c.Long ? (e2.int64Data[n2] = c.Long.fromValue(t3.int64Data[n2])).unsigned = false : "string" == typeof t3.int64Data[n2] ? e2.int64Data[n2] = parseInt(t3.int64Data[n2], 10) : "number" == typeof t3.int64Data[n2] ? e2.int64Data[n2] = t3.int64Data[n2] : "object" == typeof t3.int64Data[n2] && (e2.int64Data[n2] = new c.LongBits(t3.int64Data[n2].low >>> 0, t3.int64Data[n2].high >>> 0).toNumber());
              }
              if (null != t3.name && (e2.name = String(t3.name)), null != t3.docString && (e2.docString = String(t3.docString)), null != t3.rawData && ("string" == typeof t3.rawData ? c.base64.decode(t3.rawData, e2.rawData = c.newBuffer(c.base64.length(t3.rawData)), 0) : t3.rawData.length && (e2.rawData = t3.rawData)), t3.externalData) {
                if (!Array.isArray(t3.externalData)) throw TypeError(".onnx.TensorProto.externalData: array expected");
                for (e2.externalData = [], n2 = 0; n2 < t3.externalData.length; ++n2) {
                  if ("object" != typeof t3.externalData[n2]) throw TypeError(".onnx.TensorProto.externalData: object expected");
                  e2.externalData[n2] = l.onnx.StringStringEntryProto.fromObject(t3.externalData[n2]);
                }
              }
              switch (t3.dataLocation) {
                case "DEFAULT":
                case 0:
                  e2.dataLocation = 0;
                  break;
                case "EXTERNAL":
                case 1:
                  e2.dataLocation = 1;
              }
              if (t3.doubleData) {
                if (!Array.isArray(t3.doubleData)) throw TypeError(".onnx.TensorProto.doubleData: array expected");
                for (e2.doubleData = [], n2 = 0; n2 < t3.doubleData.length; ++n2) e2.doubleData[n2] = Number(t3.doubleData[n2]);
              }
              if (t3.uint64Data) {
                if (!Array.isArray(t3.uint64Data)) throw TypeError(".onnx.TensorProto.uint64Data: array expected");
                for (e2.uint64Data = [], n2 = 0; n2 < t3.uint64Data.length; ++n2) c.Long ? (e2.uint64Data[n2] = c.Long.fromValue(t3.uint64Data[n2])).unsigned = true : "string" == typeof t3.uint64Data[n2] ? e2.uint64Data[n2] = parseInt(t3.uint64Data[n2], 10) : "number" == typeof t3.uint64Data[n2] ? e2.uint64Data[n2] = t3.uint64Data[n2] : "object" == typeof t3.uint64Data[n2] && (e2.uint64Data[n2] = new c.LongBits(t3.uint64Data[n2].low >>> 0, t3.uint64Data[n2].high >>> 0).toNumber(true));
              }
              return e2;
            }, t2.toObject = function(t3, e2) {
              e2 || (e2 = {});
              var n2 = {};
              if ((e2.arrays || e2.defaults) && (n2.dims = [], n2.floatData = [], n2.int32Data = [], n2.stringData = [], n2.int64Data = [], n2.doubleData = [], n2.uint64Data = [], n2.externalData = []), e2.defaults && (n2.dataType = 0, n2.segment = null, n2.name = "", e2.bytes === String ? n2.rawData = "" : (n2.rawData = [], e2.bytes !== Array && (n2.rawData = c.newBuffer(n2.rawData))), n2.docString = "", n2.dataLocation = e2.enums === String ? "DEFAULT" : 0), t3.dims && t3.dims.length) {
                n2.dims = [];
                for (var r2 = 0; r2 < t3.dims.length; ++r2) "number" == typeof t3.dims[r2] ? n2.dims[r2] = e2.longs === String ? String(t3.dims[r2]) : t3.dims[r2] : n2.dims[r2] = e2.longs === String ? c.Long.prototype.toString.call(t3.dims[r2]) : e2.longs === Number ? new c.LongBits(t3.dims[r2].low >>> 0, t3.dims[r2].high >>> 0).toNumber() : t3.dims[r2];
              }
              if (null != t3.dataType && t3.hasOwnProperty("dataType") && (n2.dataType = t3.dataType), null != t3.segment && t3.hasOwnProperty("segment") && (n2.segment = l.onnx.TensorProto.Segment.toObject(t3.segment, e2)), t3.floatData && t3.floatData.length) for (n2.floatData = [], r2 = 0; r2 < t3.floatData.length; ++r2) n2.floatData[r2] = e2.json && !isFinite(t3.floatData[r2]) ? String(t3.floatData[r2]) : t3.floatData[r2];
              if (t3.int32Data && t3.int32Data.length) for (n2.int32Data = [], r2 = 0; r2 < t3.int32Data.length; ++r2) n2.int32Data[r2] = t3.int32Data[r2];
              if (t3.stringData && t3.stringData.length) for (n2.stringData = [], r2 = 0; r2 < t3.stringData.length; ++r2) n2.stringData[r2] = e2.bytes === String ? c.base64.encode(t3.stringData[r2], 0, t3.stringData[r2].length) : e2.bytes === Array ? Array.prototype.slice.call(t3.stringData[r2]) : t3.stringData[r2];
              if (t3.int64Data && t3.int64Data.length) for (n2.int64Data = [], r2 = 0; r2 < t3.int64Data.length; ++r2) "number" == typeof t3.int64Data[r2] ? n2.int64Data[r2] = e2.longs === String ? String(t3.int64Data[r2]) : t3.int64Data[r2] : n2.int64Data[r2] = e2.longs === String ? c.Long.prototype.toString.call(t3.int64Data[r2]) : e2.longs === Number ? new c.LongBits(t3.int64Data[r2].low >>> 0, t3.int64Data[r2].high >>> 0).toNumber() : t3.int64Data[r2];
              if (null != t3.name && t3.hasOwnProperty("name") && (n2.name = t3.name), null != t3.rawData && t3.hasOwnProperty("rawData") && (n2.rawData = e2.bytes === String ? c.base64.encode(t3.rawData, 0, t3.rawData.length) : e2.bytes === Array ? Array.prototype.slice.call(t3.rawData) : t3.rawData), t3.doubleData && t3.doubleData.length) for (n2.doubleData = [], r2 = 0; r2 < t3.doubleData.length; ++r2) n2.doubleData[r2] = e2.json && !isFinite(t3.doubleData[r2]) ? String(t3.doubleData[r2]) : t3.doubleData[r2];
              if (t3.uint64Data && t3.uint64Data.length) for (n2.uint64Data = [], r2 = 0; r2 < t3.uint64Data.length; ++r2) "number" == typeof t3.uint64Data[r2] ? n2.uint64Data[r2] = e2.longs === String ? String(t3.uint64Data[r2]) : t3.uint64Data[r2] : n2.uint64Data[r2] = e2.longs === String ? c.Long.prototype.toString.call(t3.uint64Data[r2]) : e2.longs === Number ? new c.LongBits(t3.uint64Data[r2].low >>> 0, t3.uint64Data[r2].high >>> 0).toNumber(true) : t3.uint64Data[r2];
              if (null != t3.docString && t3.hasOwnProperty("docString") && (n2.docString = t3.docString), t3.externalData && t3.externalData.length) for (n2.externalData = [], r2 = 0; r2 < t3.externalData.length; ++r2) n2.externalData[r2] = l.onnx.StringStringEntryProto.toObject(t3.externalData[r2], e2);
              return null != t3.dataLocation && t3.hasOwnProperty("dataLocation") && (n2.dataLocation = e2.enums === String ? l.onnx.TensorProto.DataLocation[t3.dataLocation] : t3.dataLocation), n2;
            }, t2.prototype.toJSON = function() {
              return this.constructor.toObject(this, a.util.toJSONOptions);
            }, t2.DataType = (function() {
              var t3 = {}, e2 = Object.create(t3);
              return e2[t3[0] = "UNDEFINED"] = 0, e2[t3[1] = "FLOAT"] = 1, e2[t3[2] = "UINT8"] = 2, e2[t3[3] = "INT8"] = 3, e2[t3[4] = "UINT16"] = 4, e2[t3[5] = "INT16"] = 5, e2[t3[6] = "INT32"] = 6, e2[t3[7] = "INT64"] = 7, e2[t3[8] = "STRING"] = 8, e2[t3[9] = "BOOL"] = 9, e2[t3[10] = "FLOAT16"] = 10, e2[t3[11] = "DOUBLE"] = 11, e2[t3[12] = "UINT32"] = 12, e2[t3[13] = "UINT64"] = 13, e2[t3[14] = "COMPLEX64"] = 14, e2[t3[15] = "COMPLEX128"] = 15, e2[t3[16] = "BFLOAT16"] = 16, e2;
            })(), t2.Segment = (function() {
              function t3(t4) {
                if (t4) for (var e2 = Object.keys(t4), n2 = 0; n2 < e2.length; ++n2) null != t4[e2[n2]] && (this[e2[n2]] = t4[e2[n2]]);
              }
              return t3.prototype.begin = c.Long ? c.Long.fromBits(0, 0, false) : 0, t3.prototype.end = c.Long ? c.Long.fromBits(0, 0, false) : 0, t3.create = function(e2) {
                return new t3(e2);
              }, t3.encode = function(t4, e2) {
                return e2 || (e2 = u.create()), null != t4.begin && t4.hasOwnProperty("begin") && e2.uint32(8).int64(t4.begin), null != t4.end && t4.hasOwnProperty("end") && e2.uint32(16).int64(t4.end), e2;
              }, t3.encodeDelimited = function(t4, e2) {
                return this.encode(t4, e2).ldelim();
              }, t3.decode = function(t4, e2) {
                t4 instanceof s || (t4 = s.create(t4));
                for (var n2 = void 0 === e2 ? t4.len : t4.pos + e2, r2 = new l.onnx.TensorProto.Segment(); t4.pos < n2; ) {
                  var i3 = t4.uint32();
                  switch (i3 >>> 3) {
                    case 1:
                      r2.begin = t4.int64();
                      break;
                    case 2:
                      r2.end = t4.int64();
                      break;
                    default:
                      t4.skipType(7 & i3);
                  }
                }
                return r2;
              }, t3.decodeDelimited = function(t4) {
                return t4 instanceof s || (t4 = new s(t4)), this.decode(t4, t4.uint32());
              }, t3.verify = function(t4) {
                return "object" != typeof t4 || null === t4 ? "object expected" : null != t4.begin && t4.hasOwnProperty("begin") && !(c.isInteger(t4.begin) || t4.begin && c.isInteger(t4.begin.low) && c.isInteger(t4.begin.high)) ? "begin: integer|Long expected" : null != t4.end && t4.hasOwnProperty("end") && !(c.isInteger(t4.end) || t4.end && c.isInteger(t4.end.low) && c.isInteger(t4.end.high)) ? "end: integer|Long expected" : null;
              }, t3.fromObject = function(t4) {
                if (t4 instanceof l.onnx.TensorProto.Segment) return t4;
                var e2 = new l.onnx.TensorProto.Segment();
                return null != t4.begin && (c.Long ? (e2.begin = c.Long.fromValue(t4.begin)).unsigned = false : "string" == typeof t4.begin ? e2.begin = parseInt(t4.begin, 10) : "number" == typeof t4.begin ? e2.begin = t4.begin : "object" == typeof t4.begin && (e2.begin = new c.LongBits(t4.begin.low >>> 0, t4.begin.high >>> 0).toNumber())), null != t4.end && (c.Long ? (e2.end = c.Long.fromValue(t4.end)).unsigned = false : "string" == typeof t4.end ? e2.end = parseInt(t4.end, 10) : "number" == typeof t4.end ? e2.end = t4.end : "object" == typeof t4.end && (e2.end = new c.LongBits(t4.end.low >>> 0, t4.end.high >>> 0).toNumber())), e2;
              }, t3.toObject = function(t4, e2) {
                e2 || (e2 = {});
                var n2 = {};
                if (e2.defaults) {
                  if (c.Long) {
                    var r2 = new c.Long(0, 0, false);
                    n2.begin = e2.longs === String ? r2.toString() : e2.longs === Number ? r2.toNumber() : r2;
                  } else n2.begin = e2.longs === String ? "0" : 0;
                  c.Long ? (r2 = new c.Long(0, 0, false), n2.end = e2.longs === String ? r2.toString() : e2.longs === Number ? r2.toNumber() : r2) : n2.end = e2.longs === String ? "0" : 0;
                }
                return null != t4.begin && t4.hasOwnProperty("begin") && ("number" == typeof t4.begin ? n2.begin = e2.longs === String ? String(t4.begin) : t4.begin : n2.begin = e2.longs === String ? c.Long.prototype.toString.call(t4.begin) : e2.longs === Number ? new c.LongBits(t4.begin.low >>> 0, t4.begin.high >>> 0).toNumber() : t4.begin), null != t4.end && t4.hasOwnProperty("end") && ("number" == typeof t4.end ? n2.end = e2.longs === String ? String(t4.end) : t4.end : n2.end = e2.longs === String ? c.Long.prototype.toString.call(t4.end) : e2.longs === Number ? new c.LongBits(t4.end.low >>> 0, t4.end.high >>> 0).toNumber() : t4.end), n2;
              }, t3.prototype.toJSON = function() {
                return this.constructor.toObject(this, a.util.toJSONOptions);
              }, t3;
            })(), t2.DataLocation = (function() {
              var t3 = {}, e2 = Object.create(t3);
              return e2[t3[0] = "DEFAULT"] = 0, e2[t3[1] = "EXTERNAL"] = 1, e2;
            })(), t2;
          })(), o.TensorShapeProto = (function() {
            function t2(t3) {
              if (this.dim = [], t3) for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2) null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]);
            }
            return t2.prototype.dim = c.emptyArray, t2.create = function(e2) {
              return new t2(e2);
            }, t2.encode = function(t3, e2) {
              if (e2 || (e2 = u.create()), null != t3.dim && t3.dim.length) for (var n2 = 0; n2 < t3.dim.length; ++n2) l.onnx.TensorShapeProto.Dimension.encode(t3.dim[n2], e2.uint32(10).fork()).ldelim();
              return e2;
            }, t2.encodeDelimited = function(t3, e2) {
              return this.encode(t3, e2).ldelim();
            }, t2.decode = function(t3, e2) {
              t3 instanceof s || (t3 = s.create(t3));
              for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.TensorShapeProto(); t3.pos < n2; ) {
                var i3 = t3.uint32();
                i3 >>> 3 == 1 ? (r2.dim && r2.dim.length || (r2.dim = []), r2.dim.push(l.onnx.TensorShapeProto.Dimension.decode(t3, t3.uint32()))) : t3.skipType(7 & i3);
              }
              return r2;
            }, t2.decodeDelimited = function(t3) {
              return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32());
            }, t2.verify = function(t3) {
              if ("object" != typeof t3 || null === t3) return "object expected";
              if (null != t3.dim && t3.hasOwnProperty("dim")) {
                if (!Array.isArray(t3.dim)) return "dim: array expected";
                for (var e2 = 0; e2 < t3.dim.length; ++e2) {
                  var n2 = l.onnx.TensorShapeProto.Dimension.verify(t3.dim[e2]);
                  if (n2) return "dim." + n2;
                }
              }
              return null;
            }, t2.fromObject = function(t3) {
              if (t3 instanceof l.onnx.TensorShapeProto) return t3;
              var e2 = new l.onnx.TensorShapeProto();
              if (t3.dim) {
                if (!Array.isArray(t3.dim)) throw TypeError(".onnx.TensorShapeProto.dim: array expected");
                e2.dim = [];
                for (var n2 = 0; n2 < t3.dim.length; ++n2) {
                  if ("object" != typeof t3.dim[n2]) throw TypeError(".onnx.TensorShapeProto.dim: object expected");
                  e2.dim[n2] = l.onnx.TensorShapeProto.Dimension.fromObject(t3.dim[n2]);
                }
              }
              return e2;
            }, t2.toObject = function(t3, e2) {
              e2 || (e2 = {});
              var n2 = {};
              if ((e2.arrays || e2.defaults) && (n2.dim = []), t3.dim && t3.dim.length) {
                n2.dim = [];
                for (var r2 = 0; r2 < t3.dim.length; ++r2) n2.dim[r2] = l.onnx.TensorShapeProto.Dimension.toObject(t3.dim[r2], e2);
              }
              return n2;
            }, t2.prototype.toJSON = function() {
              return this.constructor.toObject(this, a.util.toJSONOptions);
            }, t2.Dimension = (function() {
              function t3(t4) {
                if (t4) for (var e3 = Object.keys(t4), n2 = 0; n2 < e3.length; ++n2) null != t4[e3[n2]] && (this[e3[n2]] = t4[e3[n2]]);
              }
              var e2;
              return t3.prototype.dimValue = c.Long ? c.Long.fromBits(0, 0, false) : 0, t3.prototype.dimParam = "", t3.prototype.denotation = "", Object.defineProperty(t3.prototype, "value", { get: c.oneOfGetter(e2 = ["dimValue", "dimParam"]), set: c.oneOfSetter(e2) }), t3.create = function(e3) {
                return new t3(e3);
              }, t3.encode = function(t4, e3) {
                return e3 || (e3 = u.create()), null != t4.dimValue && t4.hasOwnProperty("dimValue") && e3.uint32(8).int64(t4.dimValue), null != t4.dimParam && t4.hasOwnProperty("dimParam") && e3.uint32(18).string(t4.dimParam), null != t4.denotation && t4.hasOwnProperty("denotation") && e3.uint32(26).string(t4.denotation), e3;
              }, t3.encodeDelimited = function(t4, e3) {
                return this.encode(t4, e3).ldelim();
              }, t3.decode = function(t4, e3) {
                t4 instanceof s || (t4 = s.create(t4));
                for (var n2 = void 0 === e3 ? t4.len : t4.pos + e3, r2 = new l.onnx.TensorShapeProto.Dimension(); t4.pos < n2; ) {
                  var i3 = t4.uint32();
                  switch (i3 >>> 3) {
                    case 1:
                      r2.dimValue = t4.int64();
                      break;
                    case 2:
                      r2.dimParam = t4.string();
                      break;
                    case 3:
                      r2.denotation = t4.string();
                      break;
                    default:
                      t4.skipType(7 & i3);
                  }
                }
                return r2;
              }, t3.decodeDelimited = function(t4) {
                return t4 instanceof s || (t4 = new s(t4)), this.decode(t4, t4.uint32());
              }, t3.verify = function(t4) {
                if ("object" != typeof t4 || null === t4) return "object expected";
                var e3 = {};
                if (null != t4.dimValue && t4.hasOwnProperty("dimValue") && (e3.value = 1, !(c.isInteger(t4.dimValue) || t4.dimValue && c.isInteger(t4.dimValue.low) && c.isInteger(t4.dimValue.high)))) return "dimValue: integer|Long expected";
                if (null != t4.dimParam && t4.hasOwnProperty("dimParam")) {
                  if (1 === e3.value) return "value: multiple values";
                  if (e3.value = 1, !c.isString(t4.dimParam)) return "dimParam: string expected";
                }
                return null != t4.denotation && t4.hasOwnProperty("denotation") && !c.isString(t4.denotation) ? "denotation: string expected" : null;
              }, t3.fromObject = function(t4) {
                if (t4 instanceof l.onnx.TensorShapeProto.Dimension) return t4;
                var e3 = new l.onnx.TensorShapeProto.Dimension();
                return null != t4.dimValue && (c.Long ? (e3.dimValue = c.Long.fromValue(t4.dimValue)).unsigned = false : "string" == typeof t4.dimValue ? e3.dimValue = parseInt(t4.dimValue, 10) : "number" == typeof t4.dimValue ? e3.dimValue = t4.dimValue : "object" == typeof t4.dimValue && (e3.dimValue = new c.LongBits(t4.dimValue.low >>> 0, t4.dimValue.high >>> 0).toNumber())), null != t4.dimParam && (e3.dimParam = String(t4.dimParam)), null != t4.denotation && (e3.denotation = String(t4.denotation)), e3;
              }, t3.toObject = function(t4, e3) {
                e3 || (e3 = {});
                var n2 = {};
                return e3.defaults && (n2.denotation = ""), null != t4.dimValue && t4.hasOwnProperty("dimValue") && ("number" == typeof t4.dimValue ? n2.dimValue = e3.longs === String ? String(t4.dimValue) : t4.dimValue : n2.dimValue = e3.longs === String ? c.Long.prototype.toString.call(t4.dimValue) : e3.longs === Number ? new c.LongBits(t4.dimValue.low >>> 0, t4.dimValue.high >>> 0).toNumber() : t4.dimValue, e3.oneofs && (n2.value = "dimValue")), null != t4.dimParam && t4.hasOwnProperty("dimParam") && (n2.dimParam = t4.dimParam, e3.oneofs && (n2.value = "dimParam")), null != t4.denotation && t4.hasOwnProperty("denotation") && (n2.denotation = t4.denotation), n2;
              }, t3.prototype.toJSON = function() {
                return this.constructor.toObject(this, a.util.toJSONOptions);
              }, t3;
            })(), t2;
          })(), o.TypeProto = (function() {
            function t2(t3) {
              if (t3) for (var e3 = Object.keys(t3), n2 = 0; n2 < e3.length; ++n2) null != t3[e3[n2]] && (this[e3[n2]] = t3[e3[n2]]);
            }
            var e2;
            return t2.prototype.tensorType = null, t2.prototype.denotation = "", Object.defineProperty(t2.prototype, "value", { get: c.oneOfGetter(e2 = ["tensorType"]), set: c.oneOfSetter(e2) }), t2.create = function(e3) {
              return new t2(e3);
            }, t2.encode = function(t3, e3) {
              return e3 || (e3 = u.create()), null != t3.tensorType && t3.hasOwnProperty("tensorType") && l.onnx.TypeProto.Tensor.encode(t3.tensorType, e3.uint32(10).fork()).ldelim(), null != t3.denotation && t3.hasOwnProperty("denotation") && e3.uint32(50).string(t3.denotation), e3;
            }, t2.encodeDelimited = function(t3, e3) {
              return this.encode(t3, e3).ldelim();
            }, t2.decode = function(t3, e3) {
              t3 instanceof s || (t3 = s.create(t3));
              for (var n2 = void 0 === e3 ? t3.len : t3.pos + e3, r2 = new l.onnx.TypeProto(); t3.pos < n2; ) {
                var i3 = t3.uint32();
                switch (i3 >>> 3) {
                  case 1:
                    r2.tensorType = l.onnx.TypeProto.Tensor.decode(t3, t3.uint32());
                    break;
                  case 6:
                    r2.denotation = t3.string();
                    break;
                  default:
                    t3.skipType(7 & i3);
                }
              }
              return r2;
            }, t2.decodeDelimited = function(t3) {
              return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32());
            }, t2.verify = function(t3) {
              if ("object" != typeof t3 || null === t3) return "object expected";
              if (null != t3.tensorType && t3.hasOwnProperty("tensorType")) {
                var e3 = l.onnx.TypeProto.Tensor.verify(t3.tensorType);
                if (e3) return "tensorType." + e3;
              }
              return null != t3.denotation && t3.hasOwnProperty("denotation") && !c.isString(t3.denotation) ? "denotation: string expected" : null;
            }, t2.fromObject = function(t3) {
              if (t3 instanceof l.onnx.TypeProto) return t3;
              var e3 = new l.onnx.TypeProto();
              if (null != t3.tensorType) {
                if ("object" != typeof t3.tensorType) throw TypeError(".onnx.TypeProto.tensorType: object expected");
                e3.tensorType = l.onnx.TypeProto.Tensor.fromObject(t3.tensorType);
              }
              return null != t3.denotation && (e3.denotation = String(t3.denotation)), e3;
            }, t2.toObject = function(t3, e3) {
              e3 || (e3 = {});
              var n2 = {};
              return e3.defaults && (n2.denotation = ""), null != t3.tensorType && t3.hasOwnProperty("tensorType") && (n2.tensorType = l.onnx.TypeProto.Tensor.toObject(t3.tensorType, e3), e3.oneofs && (n2.value = "tensorType")), null != t3.denotation && t3.hasOwnProperty("denotation") && (n2.denotation = t3.denotation), n2;
            }, t2.prototype.toJSON = function() {
              return this.constructor.toObject(this, a.util.toJSONOptions);
            }, t2.Tensor = (function() {
              function t3(t4) {
                if (t4) for (var e3 = Object.keys(t4), n2 = 0; n2 < e3.length; ++n2) null != t4[e3[n2]] && (this[e3[n2]] = t4[e3[n2]]);
              }
              return t3.prototype.elemType = 0, t3.prototype.shape = null, t3.create = function(e3) {
                return new t3(e3);
              }, t3.encode = function(t4, e3) {
                return e3 || (e3 = u.create()), null != t4.elemType && t4.hasOwnProperty("elemType") && e3.uint32(8).int32(t4.elemType), null != t4.shape && t4.hasOwnProperty("shape") && l.onnx.TensorShapeProto.encode(t4.shape, e3.uint32(18).fork()).ldelim(), e3;
              }, t3.encodeDelimited = function(t4, e3) {
                return this.encode(t4, e3).ldelim();
              }, t3.decode = function(t4, e3) {
                t4 instanceof s || (t4 = s.create(t4));
                for (var n2 = void 0 === e3 ? t4.len : t4.pos + e3, r2 = new l.onnx.TypeProto.Tensor(); t4.pos < n2; ) {
                  var i3 = t4.uint32();
                  switch (i3 >>> 3) {
                    case 1:
                      r2.elemType = t4.int32();
                      break;
                    case 2:
                      r2.shape = l.onnx.TensorShapeProto.decode(t4, t4.uint32());
                      break;
                    default:
                      t4.skipType(7 & i3);
                  }
                }
                return r2;
              }, t3.decodeDelimited = function(t4) {
                return t4 instanceof s || (t4 = new s(t4)), this.decode(t4, t4.uint32());
              }, t3.verify = function(t4) {
                if ("object" != typeof t4 || null === t4) return "object expected";
                if (null != t4.elemType && t4.hasOwnProperty("elemType") && !c.isInteger(t4.elemType)) return "elemType: integer expected";
                if (null != t4.shape && t4.hasOwnProperty("shape")) {
                  var e3 = l.onnx.TensorShapeProto.verify(t4.shape);
                  if (e3) return "shape." + e3;
                }
                return null;
              }, t3.fromObject = function(t4) {
                if (t4 instanceof l.onnx.TypeProto.Tensor) return t4;
                var e3 = new l.onnx.TypeProto.Tensor();
                if (null != t4.elemType && (e3.elemType = 0 | t4.elemType), null != t4.shape) {
                  if ("object" != typeof t4.shape) throw TypeError(".onnx.TypeProto.Tensor.shape: object expected");
                  e3.shape = l.onnx.TensorShapeProto.fromObject(t4.shape);
                }
                return e3;
              }, t3.toObject = function(t4, e3) {
                e3 || (e3 = {});
                var n2 = {};
                return e3.defaults && (n2.elemType = 0, n2.shape = null), null != t4.elemType && t4.hasOwnProperty("elemType") && (n2.elemType = t4.elemType), null != t4.shape && t4.hasOwnProperty("shape") && (n2.shape = l.onnx.TensorShapeProto.toObject(t4.shape, e3)), n2;
              }, t3.prototype.toJSON = function() {
                return this.constructor.toObject(this, a.util.toJSONOptions);
              }, t3;
            })(), t2;
          })(), o.OperatorSetIdProto = (function() {
            function t2(t3) {
              if (t3) for (var e2 = Object.keys(t3), n2 = 0; n2 < e2.length; ++n2) null != t3[e2[n2]] && (this[e2[n2]] = t3[e2[n2]]);
            }
            return t2.prototype.domain = "", t2.prototype.version = c.Long ? c.Long.fromBits(0, 0, false) : 0, t2.create = function(e2) {
              return new t2(e2);
            }, t2.encode = function(t3, e2) {
              return e2 || (e2 = u.create()), null != t3.domain && t3.hasOwnProperty("domain") && e2.uint32(10).string(t3.domain), null != t3.version && t3.hasOwnProperty("version") && e2.uint32(16).int64(t3.version), e2;
            }, t2.encodeDelimited = function(t3, e2) {
              return this.encode(t3, e2).ldelim();
            }, t2.decode = function(t3, e2) {
              t3 instanceof s || (t3 = s.create(t3));
              for (var n2 = void 0 === e2 ? t3.len : t3.pos + e2, r2 = new l.onnx.OperatorSetIdProto(); t3.pos < n2; ) {
                var i3 = t3.uint32();
                switch (i3 >>> 3) {
                  case 1:
                    r2.domain = t3.string();
                    break;
                  case 2:
                    r2.version = t3.int64();
                    break;
                  default:
                    t3.skipType(7 & i3);
                }
              }
              return r2;
            }, t2.decodeDelimited = function(t3) {
              return t3 instanceof s || (t3 = new s(t3)), this.decode(t3, t3.uint32());
            }, t2.verify = function(t3) {
              return "object" != typeof t3 || null === t3 ? "object expected" : null != t3.domain && t3.hasOwnProperty("domain") && !c.isString(t3.domain) ? "domain: string expected" : null != t3.version && t3.hasOwnProperty("version") && !(c.isInteger(t3.version) || t3.version && c.isInteger(t3.version.low) && c.isInteger(t3.version.high)) ? "version: integer|Long expected" : null;
            }, t2.fromObject = function(t3) {
              if (t3 instanceof l.onnx.OperatorSetIdProto) return t3;
              var e2 = new l.onnx.OperatorSetIdProto();
              return null != t3.domain && (e2.domain = String(t3.domain)), null != t3.version && (c.Long ? (e2.version = c.Long.fromValue(t3.version)).unsigned = false : "string" == typeof t3.version ? e2.version = parseInt(t3.version, 10) : "number" == typeof t3.version ? e2.version = t3.version : "object" == typeof t3.version && (e2.version = new c.LongBits(t3.version.low >>> 0, t3.version.high >>> 0).toNumber())), e2;
            }, t2.toObject = function(t3, e2) {
              e2 || (e2 = {});
              var n2 = {};
              if (e2.defaults) if (n2.domain = "", c.Long) {
                var r2 = new c.Long(0, 0, false);
                n2.version = e2.longs === String ? r2.toString() : e2.longs === Number ? r2.toNumber() : r2;
              } else n2.version = e2.longs === String ? "0" : 0;
              return null != t3.domain && t3.hasOwnProperty("domain") && (n2.domain = t3.domain), null != t3.version && t3.hasOwnProperty("version") && ("number" == typeof t3.version ? n2.version = e2.longs === String ? String(t3.version) : t3.version : n2.version = e2.longs === String ? c.Long.prototype.toString.call(t3.version) : e2.longs === Number ? new c.LongBits(t3.version.low >>> 0, t3.version.high >>> 0).toNumber() : t3.version), n2;
            }, t2.prototype.toJSON = function() {
              return this.constructor.toObject(this, a.util.toJSONOptions);
            }, t2;
          })(), o), t.exports = l;
        }, 2100: (t, e, n) => {
          t.exports = n(9482);
        }, 9482: (t, e, n) => {
          var r = e;
          function i2() {
            r.util._configure(), r.Writer._configure(r.BufferWriter), r.Reader._configure(r.BufferReader);
          }
          r.build = "minimal", r.Writer = n(1173), r.BufferWriter = n(3155), r.Reader = n(1408), r.BufferReader = n(593), r.util = n(9693), r.rpc = n(5994), r.roots = n(5054), r.configure = i2, i2();
        }, 1408: (t, e, n) => {
          t.exports = u;
          var r, i2 = n(9693), o = i2.LongBits, a = i2.utf8;
          function s(t2, e2) {
            return RangeError("index out of range: " + t2.pos + " + " + (e2 || 1) + " > " + t2.len);
          }
          function u(t2) {
            this.buf = t2, this.pos = 0, this.len = t2.length;
          }
          var c, l = "undefined" != typeof Uint8Array ? function(t2) {
            if (t2 instanceof Uint8Array || Array.isArray(t2)) return new u(t2);
            throw Error("illegal buffer");
          } : function(t2) {
            if (Array.isArray(t2)) return new u(t2);
            throw Error("illegal buffer");
          }, p = function() {
            return i2.Buffer ? function(t2) {
              return (u.create = function(t3) {
                return i2.Buffer.isBuffer(t3) ? new r(t3) : l(t3);
              })(t2);
            } : l;
          };
          function f() {
            var t2 = new o(0, 0), e2 = 0;
            if (!(this.len - this.pos > 4)) {
              for (; e2 < 3; ++e2) {
                if (this.pos >= this.len) throw s(this);
                if (t2.lo = (t2.lo | (127 & this.buf[this.pos]) << 7 * e2) >>> 0, this.buf[this.pos++] < 128) return t2;
              }
              return t2.lo = (t2.lo | (127 & this.buf[this.pos++]) << 7 * e2) >>> 0, t2;
            }
            for (; e2 < 4; ++e2) if (t2.lo = (t2.lo | (127 & this.buf[this.pos]) << 7 * e2) >>> 0, this.buf[this.pos++] < 128) return t2;
            if (t2.lo = (t2.lo | (127 & this.buf[this.pos]) << 28) >>> 0, t2.hi = (t2.hi | (127 & this.buf[this.pos]) >> 4) >>> 0, this.buf[this.pos++] < 128) return t2;
            if (e2 = 0, this.len - this.pos > 4) {
              for (; e2 < 5; ++e2) if (t2.hi = (t2.hi | (127 & this.buf[this.pos]) << 7 * e2 + 3) >>> 0, this.buf[this.pos++] < 128) return t2;
            } else for (; e2 < 5; ++e2) {
              if (this.pos >= this.len) throw s(this);
              if (t2.hi = (t2.hi | (127 & this.buf[this.pos]) << 7 * e2 + 3) >>> 0, this.buf[this.pos++] < 128) return t2;
            }
            throw Error("invalid varint encoding");
          }
          function d(t2, e2) {
            return (t2[e2 - 4] | t2[e2 - 3] << 8 | t2[e2 - 2] << 16 | t2[e2 - 1] << 24) >>> 0;
          }
          function h() {
            if (this.pos + 8 > this.len) throw s(this, 8);
            return new o(d(this.buf, this.pos += 4), d(this.buf, this.pos += 4));
          }
          u.create = p(), u.prototype._slice = i2.Array.prototype.subarray || i2.Array.prototype.slice, u.prototype.uint32 = (c = 4294967295, function() {
            if (c = (127 & this.buf[this.pos]) >>> 0, this.buf[this.pos++] < 128) return c;
            if (c = (c | (127 & this.buf[this.pos]) << 7) >>> 0, this.buf[this.pos++] < 128) return c;
            if (c = (c | (127 & this.buf[this.pos]) << 14) >>> 0, this.buf[this.pos++] < 128) return c;
            if (c = (c | (127 & this.buf[this.pos]) << 21) >>> 0, this.buf[this.pos++] < 128) return c;
            if (c = (c | (15 & this.buf[this.pos]) << 28) >>> 0, this.buf[this.pos++] < 128) return c;
            if ((this.pos += 5) > this.len) throw this.pos = this.len, s(this, 10);
            return c;
          }), u.prototype.int32 = function() {
            return 0 | this.uint32();
          }, u.prototype.sint32 = function() {
            var t2 = this.uint32();
            return t2 >>> 1 ^ -(1 & t2) | 0;
          }, u.prototype.bool = function() {
            return 0 !== this.uint32();
          }, u.prototype.fixed32 = function() {
            if (this.pos + 4 > this.len) throw s(this, 4);
            return d(this.buf, this.pos += 4);
          }, u.prototype.sfixed32 = function() {
            if (this.pos + 4 > this.len) throw s(this, 4);
            return 0 | d(this.buf, this.pos += 4);
          }, u.prototype.float = function() {
            if (this.pos + 4 > this.len) throw s(this, 4);
            var t2 = i2.float.readFloatLE(this.buf, this.pos);
            return this.pos += 4, t2;
          }, u.prototype.double = function() {
            if (this.pos + 8 > this.len) throw s(this, 4);
            var t2 = i2.float.readDoubleLE(this.buf, this.pos);
            return this.pos += 8, t2;
          }, u.prototype.bytes = function() {
            var t2 = this.uint32(), e2 = this.pos, n2 = this.pos + t2;
            if (n2 > this.len) throw s(this, t2);
            return this.pos += t2, Array.isArray(this.buf) ? this.buf.slice(e2, n2) : e2 === n2 ? new this.buf.constructor(0) : this._slice.call(this.buf, e2, n2);
          }, u.prototype.string = function() {
            var t2 = this.bytes();
            return a.read(t2, 0, t2.length);
          }, u.prototype.skip = function(t2) {
            if ("number" == typeof t2) {
              if (this.pos + t2 > this.len) throw s(this, t2);
              this.pos += t2;
            } else do {
              if (this.pos >= this.len) throw s(this);
            } while (128 & this.buf[this.pos++]);
            return this;
          }, u.prototype.skipType = function(t2) {
            switch (t2) {
              case 0:
                this.skip();
                break;
              case 1:
                this.skip(8);
                break;
              case 2:
                this.skip(this.uint32());
                break;
              case 3:
                for (; 4 != (t2 = 7 & this.uint32()); ) this.skipType(t2);
                break;
              case 5:
                this.skip(4);
                break;
              default:
                throw Error("invalid wire type " + t2 + " at offset " + this.pos);
            }
            return this;
          }, u._configure = function(t2) {
            r = t2, u.create = p(), r._configure();
            var e2 = i2.Long ? "toLong" : "toNumber";
            i2.merge(u.prototype, { int64: function() {
              return f.call(this)[e2](false);
            }, uint64: function() {
              return f.call(this)[e2](true);
            }, sint64: function() {
              return f.call(this).zzDecode()[e2](false);
            }, fixed64: function() {
              return h.call(this)[e2](true);
            }, sfixed64: function() {
              return h.call(this)[e2](false);
            } });
          };
        }, 593: (t, e, n) => {
          t.exports = o;
          var r = n(1408);
          (o.prototype = Object.create(r.prototype)).constructor = o;
          var i2 = n(9693);
          function o(t2) {
            r.call(this, t2);
          }
          o._configure = function() {
            i2.Buffer && (o.prototype._slice = i2.Buffer.prototype.slice);
          }, o.prototype.string = function() {
            var t2 = this.uint32();
            return this.buf.utf8Slice ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + t2, this.len)) : this.buf.toString("utf-8", this.pos, this.pos = Math.min(this.pos + t2, this.len));
          }, o._configure();
        }, 5054: (t) => {
          t.exports = {};
        }, 5994: (t, e, n) => {
          e.Service = n(7948);
        }, 7948: (t, e, n) => {
          t.exports = i2;
          var r = n(9693);
          function i2(t2, e2, n2) {
            if ("function" != typeof t2) throw TypeError("rpcImpl must be a function");
            r.EventEmitter.call(this), this.rpcImpl = t2, this.requestDelimited = Boolean(e2), this.responseDelimited = Boolean(n2);
          }
          (i2.prototype = Object.create(r.EventEmitter.prototype)).constructor = i2, i2.prototype.rpcCall = function t2(e2, n2, i3, o, a) {
            if (!o) throw TypeError("request must be specified");
            var s = this;
            if (!a) return r.asPromise(t2, s, e2, n2, i3, o);
            if (s.rpcImpl) try {
              return s.rpcImpl(e2, n2[s.requestDelimited ? "encodeDelimited" : "encode"](o).finish(), (function(t3, n3) {
                if (t3) return s.emit("error", t3, e2), a(t3);
                if (null !== n3) {
                  if (!(n3 instanceof i3)) try {
                    n3 = i3[s.responseDelimited ? "decodeDelimited" : "decode"](n3);
                  } catch (t4) {
                    return s.emit("error", t4, e2), a(t4);
                  }
                  return s.emit("data", n3, e2), a(null, n3);
                }
                s.end(true);
              }));
            } catch (t3) {
              return s.emit("error", t3, e2), void setTimeout((function() {
                a(t3);
              }), 0);
            }
            else setTimeout((function() {
              a(Error("already ended"));
            }), 0);
          }, i2.prototype.end = function(t2) {
            return this.rpcImpl && (t2 || this.rpcImpl(null, null, null), this.rpcImpl = null, this.emit("end").off()), this;
          };
        }, 1945: (t, e, n) => {
          t.exports = i2;
          var r = n(9693);
          function i2(t2, e2) {
            this.lo = t2 >>> 0, this.hi = e2 >>> 0;
          }
          var o = i2.zero = new i2(0, 0);
          o.toNumber = function() {
            return 0;
          }, o.zzEncode = o.zzDecode = function() {
            return this;
          }, o.length = function() {
            return 1;
          };
          var a = i2.zeroHash = "\0\0\0\0\0\0\0\0";
          i2.fromNumber = function(t2) {
            if (0 === t2) return o;
            var e2 = t2 < 0;
            e2 && (t2 = -t2);
            var n2 = t2 >>> 0, r2 = (t2 - n2) / 4294967296 >>> 0;
            return e2 && (r2 = ~r2 >>> 0, n2 = ~n2 >>> 0, ++n2 > 4294967295 && (n2 = 0, ++r2 > 4294967295 && (r2 = 0))), new i2(n2, r2);
          }, i2.from = function(t2) {
            if ("number" == typeof t2) return i2.fromNumber(t2);
            if (r.isString(t2)) {
              if (!r.Long) return i2.fromNumber(parseInt(t2, 10));
              t2 = r.Long.fromString(t2);
            }
            return t2.low || t2.high ? new i2(t2.low >>> 0, t2.high >>> 0) : o;
          }, i2.prototype.toNumber = function(t2) {
            if (!t2 && this.hi >>> 31) {
              var e2 = 1 + ~this.lo >>> 0, n2 = ~this.hi >>> 0;
              return e2 || (n2 = n2 + 1 >>> 0), -(e2 + 4294967296 * n2);
            }
            return this.lo + 4294967296 * this.hi;
          }, i2.prototype.toLong = function(t2) {
            return r.Long ? new r.Long(0 | this.lo, 0 | this.hi, Boolean(t2)) : { low: 0 | this.lo, high: 0 | this.hi, unsigned: Boolean(t2) };
          };
          var s = String.prototype.charCodeAt;
          i2.fromHash = function(t2) {
            return t2 === a ? o : new i2((s.call(t2, 0) | s.call(t2, 1) << 8 | s.call(t2, 2) << 16 | s.call(t2, 3) << 24) >>> 0, (s.call(t2, 4) | s.call(t2, 5) << 8 | s.call(t2, 6) << 16 | s.call(t2, 7) << 24) >>> 0);
          }, i2.prototype.toHash = function() {
            return String.fromCharCode(255 & this.lo, this.lo >>> 8 & 255, this.lo >>> 16 & 255, this.lo >>> 24, 255 & this.hi, this.hi >>> 8 & 255, this.hi >>> 16 & 255, this.hi >>> 24);
          }, i2.prototype.zzEncode = function() {
            var t2 = this.hi >> 31;
            return this.hi = ((this.hi << 1 | this.lo >>> 31) ^ t2) >>> 0, this.lo = (this.lo << 1 ^ t2) >>> 0, this;
          }, i2.prototype.zzDecode = function() {
            var t2 = -(1 & this.lo);
            return this.lo = ((this.lo >>> 1 | this.hi << 31) ^ t2) >>> 0, this.hi = (this.hi >>> 1 ^ t2) >>> 0, this;
          }, i2.prototype.length = function() {
            var t2 = this.lo, e2 = (this.lo >>> 28 | this.hi << 4) >>> 0, n2 = this.hi >>> 24;
            return 0 === n2 ? 0 === e2 ? t2 < 16384 ? t2 < 128 ? 1 : 2 : t2 < 2097152 ? 3 : 4 : e2 < 16384 ? e2 < 128 ? 5 : 6 : e2 < 2097152 ? 7 : 8 : n2 < 128 ? 9 : 10;
          };
        }, 9693: function(t, e, n) {
          var r = e;
          function i2(t2, e2, n2) {
            for (var r2 = Object.keys(e2), i3 = 0; i3 < r2.length; ++i3) void 0 !== t2[r2[i3]] && n2 || (t2[r2[i3]] = e2[r2[i3]]);
            return t2;
          }
          function o(t2) {
            function e2(t3, n2) {
              if (!(this instanceof e2)) return new e2(t3, n2);
              Object.defineProperty(this, "message", { get: function() {
                return t3;
              } }), Error.captureStackTrace ? Error.captureStackTrace(this, e2) : Object.defineProperty(this, "stack", { value: new Error().stack || "" }), n2 && i2(this, n2);
            }
            return (e2.prototype = Object.create(Error.prototype)).constructor = e2, Object.defineProperty(e2.prototype, "name", { get: function() {
              return t2;
            } }), e2.prototype.toString = function() {
              return this.name + ": " + this.message;
            }, e2;
          }
          r.asPromise = n(4537), r.base64 = n(7419), r.EventEmitter = n(9211), r.float = n(945), r.inquire = n(7199), r.utf8 = n(4997), r.pool = n(6662), r.LongBits = n(1945), r.isNode = Boolean(void 0 !== n.g && n.g && n.g.process && n.g.process.versions && n.g.process.versions.node), r.global = r.isNode && n.g || "undefined" != typeof window && window || "undefined" != typeof self && self || this, r.emptyArray = Object.freeze ? Object.freeze([]) : [], r.emptyObject = Object.freeze ? Object.freeze({}) : {}, r.isInteger = Number.isInteger || function(t2) {
            return "number" == typeof t2 && isFinite(t2) && Math.floor(t2) === t2;
          }, r.isString = function(t2) {
            return "string" == typeof t2 || t2 instanceof String;
          }, r.isObject = function(t2) {
            return t2 && "object" == typeof t2;
          }, r.isset = r.isSet = function(t2, e2) {
            var n2 = t2[e2];
            return !(null == n2 || !t2.hasOwnProperty(e2)) && ("object" != typeof n2 || (Array.isArray(n2) ? n2.length : Object.keys(n2).length) > 0);
          }, r.Buffer = (function() {
            try {
              var t2 = r.inquire("buffer").Buffer;
              return t2.prototype.utf8Write ? t2 : null;
            } catch (t3) {
              return null;
            }
          })(), r._Buffer_from = null, r._Buffer_allocUnsafe = null, r.newBuffer = function(t2) {
            return "number" == typeof t2 ? r.Buffer ? r._Buffer_allocUnsafe(t2) : new r.Array(t2) : r.Buffer ? r._Buffer_from(t2) : "undefined" == typeof Uint8Array ? t2 : new Uint8Array(t2);
          }, r.Array = "undefined" != typeof Uint8Array ? Uint8Array : Array, r.Long = r.global.dcodeIO && r.global.dcodeIO.Long || r.global.Long || r.inquire("long"), r.key2Re = /^true|false|0|1$/, r.key32Re = /^-?(?:0|[1-9][0-9]*)$/, r.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/, r.longToHash = function(t2) {
            return t2 ? r.LongBits.from(t2).toHash() : r.LongBits.zeroHash;
          }, r.longFromHash = function(t2, e2) {
            var n2 = r.LongBits.fromHash(t2);
            return r.Long ? r.Long.fromBits(n2.lo, n2.hi, e2) : n2.toNumber(Boolean(e2));
          }, r.merge = i2, r.lcFirst = function(t2) {
            return t2.charAt(0).toLowerCase() + t2.substring(1);
          }, r.newError = o, r.ProtocolError = o("ProtocolError"), r.oneOfGetter = function(t2) {
            for (var e2 = {}, n2 = 0; n2 < t2.length; ++n2) e2[t2[n2]] = 1;
            return function() {
              for (var t3 = Object.keys(this), n3 = t3.length - 1; n3 > -1; --n3) if (1 === e2[t3[n3]] && void 0 !== this[t3[n3]] && null !== this[t3[n3]]) return t3[n3];
            };
          }, r.oneOfSetter = function(t2) {
            return function(e2) {
              for (var n2 = 0; n2 < t2.length; ++n2) t2[n2] !== e2 && delete this[t2[n2]];
            };
          }, r.toJSONOptions = { longs: String, enums: String, bytes: String, json: true }, r._configure = function() {
            var t2 = r.Buffer;
            t2 ? (r._Buffer_from = t2.from !== Uint8Array.from && t2.from || function(e2, n2) {
              return new t2(e2, n2);
            }, r._Buffer_allocUnsafe = t2.allocUnsafe || function(e2) {
              return new t2(e2);
            }) : r._Buffer_from = r._Buffer_allocUnsafe = null;
          };
        }, 1173: (t, e, n) => {
          t.exports = p;
          var r, i2 = n(9693), o = i2.LongBits, a = i2.base64, s = i2.utf8;
          function u(t2, e2, n2) {
            this.fn = t2, this.len = e2, this.next = void 0, this.val = n2;
          }
          function c() {
          }
          function l(t2) {
            this.head = t2.head, this.tail = t2.tail, this.len = t2.len, this.next = t2.states;
          }
          function p() {
            this.len = 0, this.head = new u(c, 0, 0), this.tail = this.head, this.states = null;
          }
          var f = function() {
            return i2.Buffer ? function() {
              return (p.create = function() {
                return new r();
              })();
            } : function() {
              return new p();
            };
          };
          function d(t2, e2, n2) {
            e2[n2] = 255 & t2;
          }
          function h(t2, e2) {
            this.len = t2, this.next = void 0, this.val = e2;
          }
          function g(t2, e2, n2) {
            for (; t2.hi; ) e2[n2++] = 127 & t2.lo | 128, t2.lo = (t2.lo >>> 7 | t2.hi << 25) >>> 0, t2.hi >>>= 7;
            for (; t2.lo > 127; ) e2[n2++] = 127 & t2.lo | 128, t2.lo = t2.lo >>> 7;
            e2[n2++] = t2.lo;
          }
          function b(t2, e2, n2) {
            e2[n2] = 255 & t2, e2[n2 + 1] = t2 >>> 8 & 255, e2[n2 + 2] = t2 >>> 16 & 255, e2[n2 + 3] = t2 >>> 24;
          }
          p.create = f(), p.alloc = function(t2) {
            return new i2.Array(t2);
          }, i2.Array !== Array && (p.alloc = i2.pool(p.alloc, i2.Array.prototype.subarray)), p.prototype._push = function(t2, e2, n2) {
            return this.tail = this.tail.next = new u(t2, e2, n2), this.len += e2, this;
          }, h.prototype = Object.create(u.prototype), h.prototype.fn = function(t2, e2, n2) {
            for (; t2 > 127; ) e2[n2++] = 127 & t2 | 128, t2 >>>= 7;
            e2[n2] = t2;
          }, p.prototype.uint32 = function(t2) {
            return this.len += (this.tail = this.tail.next = new h((t2 >>>= 0) < 128 ? 1 : t2 < 16384 ? 2 : t2 < 2097152 ? 3 : t2 < 268435456 ? 4 : 5, t2)).len, this;
          }, p.prototype.int32 = function(t2) {
            return t2 < 0 ? this._push(g, 10, o.fromNumber(t2)) : this.uint32(t2);
          }, p.prototype.sint32 = function(t2) {
            return this.uint32((t2 << 1 ^ t2 >> 31) >>> 0);
          }, p.prototype.uint64 = function(t2) {
            var e2 = o.from(t2);
            return this._push(g, e2.length(), e2);
          }, p.prototype.int64 = p.prototype.uint64, p.prototype.sint64 = function(t2) {
            var e2 = o.from(t2).zzEncode();
            return this._push(g, e2.length(), e2);
          }, p.prototype.bool = function(t2) {
            return this._push(d, 1, t2 ? 1 : 0);
          }, p.prototype.fixed32 = function(t2) {
            return this._push(b, 4, t2 >>> 0);
          }, p.prototype.sfixed32 = p.prototype.fixed32, p.prototype.fixed64 = function(t2) {
            var e2 = o.from(t2);
            return this._push(b, 4, e2.lo)._push(b, 4, e2.hi);
          }, p.prototype.sfixed64 = p.prototype.fixed64, p.prototype.float = function(t2) {
            return this._push(i2.float.writeFloatLE, 4, t2);
          }, p.prototype.double = function(t2) {
            return this._push(i2.float.writeDoubleLE, 8, t2);
          };
          var m = i2.Array.prototype.set ? function(t2, e2, n2) {
            e2.set(t2, n2);
          } : function(t2, e2, n2) {
            for (var r2 = 0; r2 < t2.length; ++r2) e2[n2 + r2] = t2[r2];
          };
          p.prototype.bytes = function(t2) {
            var e2 = t2.length >>> 0;
            if (!e2) return this._push(d, 1, 0);
            if (i2.isString(t2)) {
              var n2 = p.alloc(e2 = a.length(t2));
              a.decode(t2, n2, 0), t2 = n2;
            }
            return this.uint32(e2)._push(m, e2, t2);
          }, p.prototype.string = function(t2) {
            var e2 = s.length(t2);
            return e2 ? this.uint32(e2)._push(s.write, e2, t2) : this._push(d, 1, 0);
          }, p.prototype.fork = function() {
            return this.states = new l(this), this.head = this.tail = new u(c, 0, 0), this.len = 0, this;
          }, p.prototype.reset = function() {
            return this.states ? (this.head = this.states.head, this.tail = this.states.tail, this.len = this.states.len, this.states = this.states.next) : (this.head = this.tail = new u(c, 0, 0), this.len = 0), this;
          }, p.prototype.ldelim = function() {
            var t2 = this.head, e2 = this.tail, n2 = this.len;
            return this.reset().uint32(n2), n2 && (this.tail.next = t2.next, this.tail = e2, this.len += n2), this;
          }, p.prototype.finish = function() {
            for (var t2 = this.head.next, e2 = this.constructor.alloc(this.len), n2 = 0; t2; ) t2.fn(t2.val, e2, n2), n2 += t2.len, t2 = t2.next;
            return e2;
          }, p._configure = function(t2) {
            r = t2, p.create = f(), r._configure();
          };
        }, 3155: (t, e, n) => {
          t.exports = o;
          var r = n(1173);
          (o.prototype = Object.create(r.prototype)).constructor = o;
          var i2 = n(9693);
          function o() {
            r.call(this);
          }
          function a(t2, e2, n2) {
            t2.length < 40 ? i2.utf8.write(t2, e2, n2) : e2.utf8Write ? e2.utf8Write(t2, n2) : e2.write(t2, n2);
          }
          o._configure = function() {
            o.alloc = i2._Buffer_allocUnsafe, o.writeBytesBuffer = i2.Buffer && i2.Buffer.prototype instanceof Uint8Array && "set" === i2.Buffer.prototype.set.name ? function(t2, e2, n2) {
              e2.set(t2, n2);
            } : function(t2, e2, n2) {
              if (t2.copy) t2.copy(e2, n2, 0, t2.length);
              else for (var r2 = 0; r2 < t2.length; ) e2[n2++] = t2[r2++];
            };
          }, o.prototype.bytes = function(t2) {
            i2.isString(t2) && (t2 = i2._Buffer_from(t2, "base64"));
            var e2 = t2.length >>> 0;
            return this.uint32(e2), e2 && this._push(o.writeBytesBuffer, e2, t2), this;
          }, o.prototype.string = function(t2) {
            var e2 = i2.Buffer.byteLength(t2);
            return this.uint32(e2), e2 && this._push(a, e2, t2), this;
          }, o._configure();
        }, 7714: (t, e, n) => {
          e.R = void 0;
          const r = n(6919), i2 = n(7448);
          e.R = new class {
            init() {
              return __async(this, null, function* () {
              });
            }
            createSessionHandler(t2, e2) {
              return __async(this, null, function* () {
                const n2 = new r.Session(e2);
                return yield n2.loadModel(t2), new i2.OnnxjsSessionHandler(n2);
              });
            }
          }();
        }, 4200: (t, e, n) => {
          e.c8 = e.rX = void 0;
          const r = n(1670), i2 = n(5381), o = n(2157), a = n(2306);
          e.rX = () => {
            if (("number" != typeof r.env.wasm.initTimeout || r.env.wasm.initTimeout < 0) && (r.env.wasm.initTimeout = 0), "boolean" != typeof r.env.wasm.simd && (r.env.wasm.simd = true), "boolean" != typeof r.env.wasm.proxy && (r.env.wasm.proxy = false), "number" != typeof r.env.wasm.numThreads || !Number.isInteger(r.env.wasm.numThreads) || r.env.wasm.numThreads <= 0) {
              const t2 = "undefined" == typeof navigator ? (0, i2.cpus)().length : navigator.hardwareConcurrency;
              r.env.wasm.numThreads = Math.min(4, Math.ceil((t2 || 1) / 2));
            }
          }, e.c8 = new class {
            init() {
              return __async(this, null, function* () {
                (0, e.rX)(), yield (0, o.initWasm)();
              });
            }
            createSessionHandler(t2, e2) {
              return __async(this, null, function* () {
                const n2 = new a.OnnxruntimeWebAssemblySessionHandler();
                return yield n2.loadModel(t2, e2), Promise.resolve(n2);
              });
            }
          }();
        }, 6018: function(t, e, n) {
          var r = this && this.__createBinding || (Object.create ? function(t2, e2, n2, r2) {
            void 0 === r2 && (r2 = n2);
            var i3 = Object.getOwnPropertyDescriptor(e2, n2);
            i3 && !("get" in i3 ? !e2.__esModule : i3.writable || i3.configurable) || (i3 = { enumerable: true, get: function() {
              return e2[n2];
            } }), Object.defineProperty(t2, r2, i3);
          } : function(t2, e2, n2, r2) {
            void 0 === r2 && (r2 = n2), t2[r2] = e2[n2];
          }), i2 = this && this.__exportStar || function(t2, e2) {
            for (var n2 in t2) "default" === n2 || Object.prototype.hasOwnProperty.call(e2, n2) || r(e2, t2, n2);
          };
          Object.defineProperty(e, "__esModule", { value: true }), i2(n(1670), e);
          const o = n(1670);
          {
            const t2 = n(7714).R;
            (0, o.registerBackend)("webgl", t2, -10);
          }
          {
            const t2 = n(4200).c8;
            (0, o.registerBackend)("cpu", t2, 10), (0, o.registerBackend)("wasm", t2, 10), (0, o.registerBackend)("xnnpack", t2, 9);
          }
        }, 246: (t, e) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.createAttributeWithCacheKey = void 0;
          class n {
            constructor(t2) {
              Object.assign(this, t2);
            }
            get cacheKey() {
              return this._cacheKey || (this._cacheKey = Object.getOwnPropertyNames(this).sort().map(((t2) => `${this[t2]}`)).join(";")), this._cacheKey;
            }
          }
          e.createAttributeWithCacheKey = (t2) => new n(t2);
        }, 7778: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.Attribute = void 0;
          const r = n(1446), i2 = n(9395), o = n(9162), a = n(2517);
          var s = i2.onnxruntime.experimental.fbs;
          class u {
            constructor(t2) {
              if (this._attributes = /* @__PURE__ */ new Map(), null != t2) {
                for (const e2 of t2) e2 instanceof r.onnx.AttributeProto ? this._attributes.set(e2.name, [u.getValue(e2), u.getType(e2)]) : e2 instanceof s.Attribute && this._attributes.set(e2.name(), [u.getValue(e2), u.getType(e2)]);
                if (this._attributes.size < t2.length) throw new Error("duplicated attribute names");
              }
            }
            set(t2, e2, n2) {
              this._attributes.set(t2, [n2, e2]);
            }
            delete(t2) {
              this._attributes.delete(t2);
            }
            getFloat(t2, e2) {
              return this.get(t2, "float", e2);
            }
            getInt(t2, e2) {
              return this.get(t2, "int", e2);
            }
            getString(t2, e2) {
              return this.get(t2, "string", e2);
            }
            getTensor(t2, e2) {
              return this.get(t2, "tensor", e2);
            }
            getFloats(t2, e2) {
              return this.get(t2, "floats", e2);
            }
            getInts(t2, e2) {
              return this.get(t2, "ints", e2);
            }
            getStrings(t2, e2) {
              return this.get(t2, "strings", e2);
            }
            getTensors(t2, e2) {
              return this.get(t2, "tensors", e2);
            }
            get(t2, e2, n2) {
              const r2 = this._attributes.get(t2);
              if (void 0 === r2) {
                if (void 0 !== n2) return n2;
                throw new Error(`required attribute not found: ${t2}`);
              }
              if (r2[1] !== e2) throw new Error(`type mismatch: expected ${e2} but got ${r2[1]}`);
              return r2[0];
            }
            static getType(t2) {
              const e2 = t2 instanceof r.onnx.AttributeProto ? t2.type : t2.type();
              switch (e2) {
                case r.onnx.AttributeProto.AttributeType.FLOAT:
                  return "float";
                case r.onnx.AttributeProto.AttributeType.INT:
                  return "int";
                case r.onnx.AttributeProto.AttributeType.STRING:
                  return "string";
                case r.onnx.AttributeProto.AttributeType.TENSOR:
                  return "tensor";
                case r.onnx.AttributeProto.AttributeType.FLOATS:
                  return "floats";
                case r.onnx.AttributeProto.AttributeType.INTS:
                  return "ints";
                case r.onnx.AttributeProto.AttributeType.STRINGS:
                  return "strings";
                case r.onnx.AttributeProto.AttributeType.TENSORS:
                  return "tensors";
                default:
                  throw new Error(`attribute type is not supported yet: ${r.onnx.AttributeProto.AttributeType[e2]}`);
              }
            }
            static getValue(t2) {
              const e2 = t2 instanceof r.onnx.AttributeProto ? t2.type : t2.type();
              if (e2 === r.onnx.AttributeProto.AttributeType.GRAPH || e2 === r.onnx.AttributeProto.AttributeType.GRAPHS) throw new Error("graph attribute is not supported yet");
              const n2 = this.getValueNoCheck(t2);
              if (e2 === r.onnx.AttributeProto.AttributeType.INT && a.LongUtil.isLong(n2)) return a.LongUtil.longToNumber(n2);
              if (e2 === r.onnx.AttributeProto.AttributeType.INTS) {
                const t3 = n2, e3 = new Array(t3.length);
                for (let n3 = 0; n3 < t3.length; n3++) {
                  const r2 = t3[n3];
                  e3[n3] = a.LongUtil.longToNumber(r2);
                }
                return e3;
              }
              if (e2 === r.onnx.AttributeProto.AttributeType.TENSOR) return t2 instanceof r.onnx.AttributeProto ? o.Tensor.fromProto(n2) : o.Tensor.fromOrtTensor(n2);
              if (e2 === r.onnx.AttributeProto.AttributeType.TENSORS) {
                if (t2 instanceof r.onnx.AttributeProto) return n2.map(((t3) => o.Tensor.fromProto(t3)));
                if (t2 instanceof s.Attribute) return n2.map(((t3) => o.Tensor.fromOrtTensor(t3)));
              }
              if (e2 === r.onnx.AttributeProto.AttributeType.STRING && t2 instanceof r.onnx.AttributeProto) {
                const t3 = n2;
                return (0, a.decodeUtf8String)(t3);
              }
              return e2 === r.onnx.AttributeProto.AttributeType.STRINGS && t2 instanceof r.onnx.AttributeProto ? n2.map(a.decodeUtf8String) : n2;
            }
            static getValueNoCheck(t2) {
              return t2 instanceof r.onnx.AttributeProto ? this.getValueNoCheckFromOnnxFormat(t2) : this.getValueNoCheckFromOrtFormat(t2);
            }
            static getValueNoCheckFromOnnxFormat(t2) {
              switch (t2.type) {
                case r.onnx.AttributeProto.AttributeType.FLOAT:
                  return t2.f;
                case r.onnx.AttributeProto.AttributeType.INT:
                  return t2.i;
                case r.onnx.AttributeProto.AttributeType.STRING:
                  return t2.s;
                case r.onnx.AttributeProto.AttributeType.TENSOR:
                  return t2.t;
                case r.onnx.AttributeProto.AttributeType.GRAPH:
                  return t2.g;
                case r.onnx.AttributeProto.AttributeType.FLOATS:
                  return t2.floats;
                case r.onnx.AttributeProto.AttributeType.INTS:
                  return t2.ints;
                case r.onnx.AttributeProto.AttributeType.STRINGS:
                  return t2.strings;
                case r.onnx.AttributeProto.AttributeType.TENSORS:
                  return t2.tensors;
                case r.onnx.AttributeProto.AttributeType.GRAPHS:
                  return t2.graphs;
                default:
                  throw new Error(`unsupported attribute type: ${r.onnx.AttributeProto.AttributeType[t2.type]}`);
              }
            }
            static getValueNoCheckFromOrtFormat(t2) {
              switch (t2.type()) {
                case s.AttributeType.FLOAT:
                  return t2.f();
                case s.AttributeType.INT:
                  return t2.i();
                case s.AttributeType.STRING:
                  return t2.s();
                case s.AttributeType.TENSOR:
                  return t2.t();
                case s.AttributeType.GRAPH:
                  return t2.g();
                case s.AttributeType.FLOATS:
                  return t2.floatsArray();
                case s.AttributeType.INTS: {
                  const e2 = [];
                  for (let n2 = 0; n2 < t2.intsLength(); n2++) e2.push(t2.ints(n2));
                  return e2;
                }
                case s.AttributeType.STRINGS: {
                  const e2 = [];
                  for (let n2 = 0; n2 < t2.stringsLength(); n2++) e2.push(t2.strings(n2));
                  return e2;
                }
                case s.AttributeType.TENSORS: {
                  const e2 = [];
                  for (let n2 = 0; n2 < t2.tensorsLength(); n2++) e2.push(t2.tensors(n2));
                  return e2;
                }
                default:
                  throw new Error(`unsupported attribute type: ${s.AttributeType[t2.type()]}`);
              }
            }
          }
          e.Attribute = u;
        }, 7091: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.resolveBackend = e.backend = void 0;
          const r = n(5038), i2 = /* @__PURE__ */ new Map();
          function o(t2) {
            return __async(this, null, function* () {
              const n2 = e.backend;
              if (void 0 !== n2[t2] && (function(t3) {
                const e2 = t3;
                return "initialize" in e2 && "function" == typeof e2.initialize && "createSessionHandler" in e2 && "function" == typeof e2.createSessionHandler && "dispose" in e2 && "function" == typeof e2.dispose;
              })(n2[t2])) {
                const e2 = n2[t2];
                let r2 = e2.initialize();
                if ("object" == typeof r2 && "then" in r2 && (r2 = yield r2), r2) return i2.set(t2, e2), e2;
              }
            });
          }
          e.backend = { webgl: new r.WebGLBackend() }, e.resolveBackend = function t2(e2) {
            return __async(this, null, function* () {
              if (!e2) return t2(["webgl"]);
              {
                const t3 = "string" == typeof e2 ? [e2] : e2;
                for (const e3 of t3) {
                  const t4 = i2.get(e3);
                  if (t4) return t4;
                  const n2 = yield o(e3);
                  if (n2) return n2;
                }
              }
              throw new Error("no available backend to use");
            });
          };
        }, 5038: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.WebGLBackend = void 0;
          const r = n(1670), i2 = n(6231), o = n(6416), a = n(7305);
          e.WebGLBackend = class {
            get contextId() {
              return r.env.webgl.contextId;
            }
            set contextId(t2) {
              r.env.webgl.contextId = t2;
            }
            get matmulMaxBatchSize() {
              return r.env.webgl.matmulMaxBatchSize;
            }
            set matmulMaxBatchSize(t2) {
              r.env.webgl.matmulMaxBatchSize = t2;
            }
            get textureCacheMode() {
              return r.env.webgl.textureCacheMode;
            }
            set textureCacheMode(t2) {
              r.env.webgl.textureCacheMode = t2;
            }
            get pack() {
              return r.env.webgl.pack;
            }
            set pack(t2) {
              r.env.webgl.pack = t2;
            }
            get async() {
              return r.env.webgl.async;
            }
            set async(t2) {
              r.env.webgl.async = t2;
            }
            initialize() {
              try {
                return this.glContext = (0, a.createWebGLContext)(this.contextId), "number" != typeof this.matmulMaxBatchSize && (this.matmulMaxBatchSize = 16), "string" != typeof this.textureCacheMode && (this.textureCacheMode = "full"), "boolean" != typeof this.pack && (this.pack = false), "boolean" != typeof this.async && (this.async = false), i2.Logger.setWithEnv(r.env), i2.Logger.verbose("WebGLBackend", `Created WebGLContext: ${typeof this.glContext} with matmulMaxBatchSize: ${this.matmulMaxBatchSize}; textureCacheMode: ${this.textureCacheMode}; pack: ${this.pack}; async: ${this.async}.`), true;
              } catch (t2) {
                return i2.Logger.warning("WebGLBackend", `Unable to initialize WebGLBackend. ${t2}`), false;
              }
            }
            createSessionHandler(t2) {
              return new o.WebGLSessionHandler(this, t2);
            }
            dispose() {
              this.glContext.dispose();
            }
          };
        }, 5107: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.CoordsGlslLib = void 0;
          const r = n(2517), i2 = n(8520), o = n(5060), a = n(7859), s = n(9390);
          class u extends i2.GlslLib {
            constructor(t2) {
              super(t2);
            }
            getFunctions() {
              return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, this.offsetToCoords()), this.coordsToOffset()), this.toVec()), this.valueFrom()), this.getCommonUtilFuncs()), this.getInputsSamplingSnippets()), this.getOutputSamplingSnippet());
            }
            getCustomTypes() {
              return {};
            }
            offsetToCoords() {
              return { offsetToCoords: new i2.GlslLibRoutine("\n      vec2 offsetToCoords(int offset, int width, int height) {\n        int t = offset / width;\n        int s = offset - t*width;\n        vec2 coords = (vec2(s,t) + vec2(0.5,0.5)) / vec2(width, height);\n        return coords;\n      }\n      ") };
            }
            coordsToOffset() {
              return { coordsToOffset: new i2.GlslLibRoutine("\n      int coordsToOffset(vec2 coords, int width, int height) {\n        float s = coords.s * float(width);\n        float t = coords.t * float(height);\n        int offset = int(t) * width + int(s);\n        return offset;\n      }\n      ") };
            }
            getOutputSamplingSnippet() {
              const t2 = this.context.outputTextureLayout;
              return t2.isPacked ? this.getPackedOutputSamplingSnippet(t2) : this.getUnpackedOutputSamplingSnippet(t2);
            }
            getPackedOutputSamplingSnippet(t2) {
              const e2 = t2.unpackedShape, n2 = [t2.width, t2.height], r2 = {}, a2 = "getOutputCoords";
              switch (e2.length) {
                case 0:
                  r2[a2] = this.getOutputScalarCoords();
                  break;
                case 1:
                  r2[a2] = this.getOutputPacked1DCoords(e2, n2);
                  break;
                case 2:
                  r2[a2] = this.getOutputPacked2DCoords(e2, n2);
                  break;
                case 3:
                  r2[a2] = this.getOutputPacked3DCoords(e2, n2);
                  break;
                default:
                  r2[a2] = this.getOutputPackedNDCoords(e2, n2);
              }
              const s2 = `
      void setOutput(vec4 val) {
        ${(0, o.getGlsl)(this.context.glContext.version).output} = val;
      }
    `;
              return r2.floatTextureSetRGBA = new i2.GlslLibRoutine(s2), r2;
            }
            getUnpackedOutputSamplingSnippet(t2) {
              const e2 = t2.unpackedShape, n2 = [t2.width, t2.height], r2 = {}, a2 = "getOutputCoords";
              switch (e2.length) {
                case 0:
                  r2[a2] = this.getOutputScalarCoords();
                  break;
                case 1:
                  r2[a2] = this.getOutputUnpacked1DCoords(e2, n2);
                  break;
                case 2:
                  r2[a2] = this.getOutputUnpacked2DCoords(e2, n2);
                  break;
                case 3:
                  r2[a2] = this.getOutputUnpacked3DCoords(e2, n2);
                  break;
                case 4:
                  r2[a2] = this.getOutputUnpacked4DCoords(e2, n2);
                  break;
                case 5:
                  r2[a2] = this.getOutputUnpacked5DCoords(e2, n2);
                  break;
                case 6:
                  r2[a2] = this.getOutputUnpacked6DCoords(e2, n2);
                  break;
                default:
                  throw new Error(`Unsupported output dimensionality: ${e2.length}`);
              }
              const s2 = `
        void setOutput(float val) {
          ${(0, o.getGlsl)(this.context.glContext.version).output} = vec4(val, 0, 0, 0);
        }
    `;
              return r2.floatTextureSetR = new i2.GlslLibRoutine(s2), r2;
            }
            getOutputScalarCoords() {
              return new i2.GlslLibRoutine("\n      int getOutputCoords() {\n        return 0;\n      }\n    ");
            }
            getOutputPacked1DCoords(t2, e2) {
              const n2 = e2;
              let r2 = "";
              return 1 === n2[0] ? (r2 = `
          int getOutputCoords() {
            return 2 * int(TexCoords.y * ${n2[1]}.0);
          }
        `, new i2.GlslLibRoutine(r2)) : 1 === n2[1] ? (r2 = `
          int getOutputCoords() {
            return 2 * int(TexCoords.x * ${n2[0]}.0);
          }
        `, new i2.GlslLibRoutine(r2)) : (r2 = `
        int getOutputCoords() {
          ivec2 resTexRC = ivec2(TexCoords.xy *
                                 vec2(${n2[0]}, ${n2[1]}));
          return 2 * (resTexRC.y * ${n2[0]} + resTexRC.x);
        }
      `, new i2.GlslLibRoutine(r2));
            }
            getOutputPacked2DCoords(t2, e2) {
              let n2 = "";
              if (r.ArrayUtil.arraysEqual(t2, e2)) return n2 = `
        ivec2 getOutputCoords() {
          return 2 * ivec2(TexCoords.xy * vec2(${e2[0]}, ${e2[1]}));
        }
      `, new i2.GlslLibRoutine(n2);
              const o2 = e2, a2 = Math.ceil(t2[1] / 2);
              return n2 = `
        ivec2 getOutputCoords() {
          ivec2 resTexRC = ivec2(TexCoords.xy *
                                vec2(${o2[0]}, ${o2[1]}));

          int index = resTexRC.y * ${o2[0]} + resTexRC.x;

          // reverse r and c order for packed texture
          int r = imod(index, ${a2}) * 2;
          int c = 2 * (index / ${a2});

          return ivec2(r, c);
        }
      `, new i2.GlslLibRoutine(n2);
            }
            getOutputPacked3DCoords(t2, e2) {
              const n2 = [e2[0], e2[1]], r2 = Math.ceil(t2[2] / 2), o2 = r2 * Math.ceil(t2[1] / 2), a2 = `
        ivec3 getOutputCoords() {
          ivec2 resTexRC = ivec2(TexCoords.xy *
                                vec2(${n2[0]}, ${n2[1]}));
          int index = resTexRC.y * ${n2[0]} + resTexRC.x;

          int b = index / ${o2};
          index -= b * ${o2};

          // reverse r and c order for packed texture
          int r = imod(index, ${r2}) * 2;
          int c = 2 * (index / ${r2});

          return ivec3(b, r, c);
        }
      `;
              return new i2.GlslLibRoutine(a2);
            }
            getOutputPackedNDCoords(t2, e2) {
              const n2 = [e2[0], e2[1]], r2 = Math.ceil(t2[t2.length - 1] / 2), o2 = r2 * Math.ceil(t2[t2.length - 2] / 2);
              let a2 = o2, s2 = "", u2 = "b, r, c";
              for (let e3 = 2; e3 < t2.length - 1; e3++) a2 *= t2[t2.length - e3 - 1], s2 = `
      int b${e3} = index / ${a2};
      index -= b${e3} * ${a2};
    ` + s2, u2 = `b${e3}, ` + u2;
              const c = `
      ivec${t2.length} getOutputCoords() {
        ivec2 resTexRC = ivec2(TexCoords.xy *
                              vec2(${n2[0]}, ${n2[1]}));
        int index = resTexRC.y * ${n2[0]} + resTexRC.x;

        ${s2}

        int b = index / ${o2};
        index -= b * ${o2};

        // reverse r and c order for packed texture
        int r = imod(index, ${r2}) * 2;
        int c = 2 * (index / ${r2});

        return ivec${t2.length}(${u2});
      }
    `;
              return new i2.GlslLibRoutine(c);
            }
            getOutputUnpacked1DCoords(t2, e2) {
              const n2 = `
        int getOutputCoords() {
          ivec2 resTexRC = ivec2(TexCoords.xy *
                                vec2(${e2[0]}, ${e2[1]}));
          return resTexRC.y * ${e2[0]} + resTexRC.x;
        }
      `;
              return new i2.GlslLibRoutine(n2);
            }
            getOutputUnpacked2DCoords(t2, e2) {
              const n2 = `
        ivec2 getOutputCoords() {
          ivec2 resTexRC = ivec2(TexCoords.xy *
                                vec2(${e2[0]}, ${e2[1]}));
          int index = resTexRC.y * ${e2[0]} + resTexRC.x;
          int r = index / ${t2[1]};
          int c = index - r * ${t2[1]};
          return ivec2(r, c);
        }
      `;
              return new i2.GlslLibRoutine(n2);
            }
            getOutputUnpacked3DCoords(t2, e2) {
              let n2 = "";
              const r2 = t2.length;
              let o2 = null;
              r2 < 2 && (o2 = []), o2 = new Array(r2 - 1), o2[r2 - 2] = t2[r2 - 1];
              for (let e3 = r2 - 3; e3 >= 0; --e3) o2[e3] = o2[e3 + 1] * t2[e3 + 1];
              const a2 = ["r", "c", "d"], s2 = o2.map(((t3, e3) => `int ${a2[e3]} = index / ${t3}; ${e3 === o2.length - 1 ? `int ${a2[e3 + 1]} = index - ${a2[e3]} * ${t3}` : `index -= ${a2[e3]} * ${t3}`};`)).join("");
              return n2 = `
        ivec3 getOutputCoords() {
          ivec2 resTexRC = ivec2(TexCoords.xy *
                                vec2(${e2[0]}, ${e2[1]}));
          int index = resTexRC.y * ${e2[0]} + resTexRC.x;
          ${s2}
          return ivec3(r, c, d);
        }
      `, new i2.GlslLibRoutine(n2);
            }
            getOutputUnpacked4DCoords(t2, e2) {
              let n2 = "";
              const r2 = t2.length;
              let o2 = null;
              r2 < 2 && (o2 = []), o2 = new Array(r2 - 1), o2[r2 - 2] = t2[r2 - 1];
              for (let e3 = r2 - 3; e3 >= 0; --e3) o2[e3] = o2[e3 + 1] * t2[e3 + 1];
              const a2 = ["r", "c", "d", "d2"], s2 = o2.map(((t3, e3) => `int ${a2[e3]} = index / ${t3}; ${e3 === o2.length - 1 ? `int ${a2[e3 + 1]} = index - ${a2[e3]} * ${t3}` : `index -= ${a2[e3]} * ${t3}`};`)).join("");
              return n2 = `
      ivec4 getOutputCoords() {
          ivec2 resTexRC = ivec2(TexCoords.xy *
                                vec2(${e2[0]}, ${e2[1]}));
          int index = resTexRC.y * ${e2[0]} + resTexRC.x;
          ${s2}
          return ivec4(r, c, d, d2);
        }
      `, new i2.GlslLibRoutine(n2);
            }
            getOutputUnpacked5DCoords(t2, e2) {
              let n2 = "";
              const r2 = t2.length;
              let o2 = null;
              r2 < 2 && (o2 = []), o2 = new Array(r2 - 1), o2[r2 - 2] = t2[r2 - 1];
              for (let e3 = r2 - 3; e3 >= 0; --e3) o2[e3] = o2[e3 + 1] * t2[e3 + 1];
              const a2 = ["r", "c", "d", "d2", "d3"], s2 = o2.map(((t3, e3) => `int ${a2[e3]} = index / ${t3}; ${e3 === o2.length - 1 ? `int ${a2[e3 + 1]} = index - ${a2[e3]} * ${t3}` : `index -= ${a2[e3]} * ${t3}`};`)).join("");
              return n2 = `
      ivec5 getOutputCoords() {
          ivec2 resTexRC = ivec2(TexCoords.xy *
                                vec2(${e2[0]}, ${e2[1]}));
          int index = resTexRC.y * ${e2[0]} + resTexRC.x;
          ${s2}
          return ivec5(r, c, d, d2, d3);
        }
      `, new i2.GlslLibRoutine(n2);
            }
            getOutputUnpacked6DCoords(t2, e2) {
              let n2 = "";
              const r2 = t2.length;
              let o2 = null;
              r2 < 2 && (o2 = []), o2 = new Array(r2 - 1), o2[r2 - 2] = t2[r2 - 1];
              for (let e3 = r2 - 3; e3 >= 0; --e3) o2[e3] = o2[e3 + 1] * t2[e3 + 1];
              const a2 = ["r", "c", "d", "d2", "d3", "d4"], s2 = o2.map(((t3, e3) => `int ${a2[e3]} = index / ${t3}; ${e3 === o2.length - 1 ? `int ${a2[e3 + 1]} = index - ${a2[e3]} * ${t3}` : `index -= ${a2[e3]} * ${t3}`};`)).join("");
              return n2 = `
     ivec6 getOutputCoords() {
         ivec2 resTexRC = ivec2(TexCoords.xy *
                               vec2(${e2[0]}, ${e2[1]}));
         int index = resTexRC.y * ${e2[0]} + resTexRC.x;
         ${s2}
         return ivec6(r, c, d, d2, d3, d4);
       }
     `, new i2.GlslLibRoutine(n2);
            }
            getCommonUtilFuncs() {
              const t2 = {};
              let e2 = "uvFromFlat";
              t2[e2] = new i2.GlslLibRoutine("\n    vec2 uvFromFlat(int texNumR, int texNumC, int index) {\n      int texC = index / texNumR;\n      int texR = index - texC * texNumR;\n      // TODO: swap texR, texC order in following function so row is corresponding to u and column is corresponding to\n      //       v.\n      return (vec2(texR, texC) + halfCR) / vec2(texNumR, texNumC);\n    }\n    "), e2 = "packedUVfrom1D", t2[e2] = new i2.GlslLibRoutine("\n      vec2 packedUVfrom1D(int texNumR, int texNumC, int index) {\n        int texelIndex = index / 2;\n        int texR = texelIndex / texNumC;\n        int texC = texelIndex - texR * texNumC;\n        return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n      }\n      "), e2 = "packedUVfrom2D", t2[e2] = new i2.GlslLibRoutine("\n      vec2 packedUVfrom2D(int texNumR, int texNumC, int texelsInLogicalRow, int row, int col) {\n        int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);\n        int texR = texelIndex / texNumC;\n        int texC = texelIndex - texR * texNumC;\n        return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n      }\n      "), e2 = "packedUVfrom3D", t2[e2] = new i2.GlslLibRoutine("\n      vec2 packedUVfrom3D(int texNumR, int texNumC,\n          int texelsInBatch, int texelsInLogicalRow, int b,\n          int row, int col) {\n        int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);\n        int texR = index / texNumC;\n        int texC = index - texR * texNumC;\n        return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n      }\n      "), e2 = "sampleTexture";
              const n2 = (0, o.getGlsl)(this.context.glContext.version);
              return t2[e2] = new i2.GlslLibRoutine(`
        float sampleTexture(sampler2D textureSampler, vec2 uv) {
            return ${n2.texture2D}(textureSampler, uv).r;
        }`), t2;
            }
            getInputsSamplingSnippets() {
              const t2 = {}, e2 = this.context.outputTextureLayout;
              return this.context.programInfo.inputNames.forEach(((n2, r2) => {
                const i3 = this.context.inputTextureLayouts[r2], o2 = (0, s.generateShaderFuncNameFromInputSamplerName)(n2);
                i3.isPacked ? t2[o2] = this.getPackedSamplerFromInput(o2, n2, i3) : t2[o2] = this.getUnpackedSamplerFromInput(o2, n2, i3);
                const a2 = (0, s.generateShaderFuncNameFromInputSamplerNameAtOutCoords)(n2);
                i3.unpackedShape.length <= e2.unpackedShape.length && (i3.isPacked ? t2[a2] = this.getPackedSamplerAtOutputCoords(a2, i3, e2, n2) : t2[a2] = this.getUnpackedSamplerAtOutputCoords(a2, i3, e2, n2));
              })), t2;
            }
            getPackedSamplerAtOutputCoords(t2, e2, n2, o2) {
              const a2 = e2.unpackedShape, u2 = n2.unpackedShape, c = o2, l = (0, s.generateShaderFuncNameFromInputSamplerName)(c), p = a2.length, f = u2.length, d = r.BroadcastUtil.getBroadcastDims(a2, u2), h = (0, s.getCoordsDataType)(f), g = f - p;
              let b;
              const m = (0, s.getGlChannels)();
              b = 0 === p ? "" : f < 2 && d.length >= 1 ? "coords = 0;" : d.map(((t3) => `coords.${m[t3 + g]} = 0;`)).join("\n");
              let y = "";
              y = f < 2 && p > 0 ? "coords" : a2.map(((t3, e3) => `coords.${m[e3 + g]}`)).join(", ");
              let _ = "return outputValue;";
              const v = 1 === r.ShapeUtil.size(a2), w = 1 === r.ShapeUtil.size(u2);
              if (1 !== p || v || w) {
                if (v && !w) _ = 1 === f ? "\n          return vec4(outputValue.x, outputValue.x, 0., 0.);\n        " : "\n          return vec4(outputValue.x);\n        ";
                else if (d.length) {
                  const t3 = p - 2, e3 = p - 1;
                  d.indexOf(t3) > -1 && d.indexOf(e3) > -1 ? _ = "return vec4(outputValue.x);" : d.indexOf(t3) > -1 ? _ = "return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);" : d.indexOf(e3) > -1 && (_ = "return vec4(outputValue.xx, outputValue.zz);");
                }
              } else _ = "\n        return vec4(outputValue.xy, outputValue.xy);\n      ";
              const x = `
      vec4 ${t2}() {
        ${h} coords = getOutputCoords();
        
        int lastDim = coords.${m[f - 1]};
        coords.${m[f - 1]} = coords.${m[f - 2]};
        coords.${m[f - 2]} = lastDim;
      
        ${b}
        vec4 outputValue = ${l}(${y});
        ${_}
      }
    `;
              return new i2.GlslLibRoutine(x, ["coordinates.getOutputCoords"]);
            }
            getUnpackedSamplerAtOutputCoords(t2, e2, n2, o2) {
              const a2 = [n2.width, n2.height], u2 = [e2.width, e2.height], c = e2.unpackedShape.length, l = n2.unpackedShape.length, p = e2.unpackedShape, f = n2.unpackedShape, d = (0, s.generateShaderFuncNameFromInputSamplerName)(o2);
              if (c === l && r.ArrayUtil.arraysEqual(u2, a2)) {
                const e3 = `
          float ${t2}() {
            return sampleTexture(${o2}, TexCoords);
          }
        `;
                return new i2.GlslLibRoutine(e3, ["coordinates.sampleTexture"]);
              }
              const h = (0, s.getCoordsDataType)(l), g = r.BroadcastUtil.getBroadcastDims(p, f), b = l - c;
              let m;
              const y = (0, s.getGlChannels)();
              m = 0 === c ? "" : l < 2 && g.length >= 1 ? "coords = 0;" : g.map(((t3) => `coords.${y[t3 + b]} = 0;`)).join("\n");
              let _ = "";
              _ = l < 2 && c > 0 ? "coords" : e2.unpackedShape.map(((t3, e3) => `coords.${y[e3 + b]}`)).join(", ");
              const v = `
        float ${t2}() {
          ${h} coords = getOutputCoords();
          ${m}
          return ${d}(${_});
        }
      `;
              return new i2.GlslLibRoutine(v, ["coordinates.getOutputCoords"]);
            }
            getPackedSamplerFromInput(t2, e2, n2) {
              switch (n2.unpackedShape.length) {
                case 0:
                  return this.getPackedSamplerScalar(t2, e2);
                case 1:
                  return this.getPackedSampler1D(t2, e2, n2);
                case 2:
                  return this.getPackedSampler2D(t2, e2, n2);
                case 3:
                  return this.getPackedSampler3D(t2, e2, n2);
                default:
                  return this.getPackedSamplerND(t2, e2, n2);
              }
            }
            getUnpackedSamplerFromInput(t2, e2, n2) {
              const r2 = n2.unpackedShape;
              switch (r2.length) {
                case 0:
                  return this.getUnpackedSamplerScalar(t2, e2, n2);
                case 1:
                  return this.getUnpackedSampler1D(t2, e2, n2);
                case 2:
                  return this.getUnpackedSampler2D(t2, e2, n2);
                case 3:
                  return this.getUnpackedSampler3D(t2, e2, n2);
                case 4:
                  return this.getUnpackedSampler4D(t2, e2, n2);
                case 5:
                  return this.getUnpackedSampler5D(t2, e2, n2);
                case 6:
                  return this.getUnpackedSampler6D(t2, e2, n2);
                default:
                  throw new Error(`Unsupported dimension ${r2.length}-D`);
              }
            }
            getPackedSamplerScalar(t2, e2) {
              const n2 = `
          vec4 ${t2}() {
            return ${(0, o.getGlsl)(this.context.glContext.version).texture2D}(${e2}, halfCR);
          }
        `;
              return new i2.GlslLibRoutine(n2);
            }
            getPackedSampler1D(t2, e2, n2) {
              const r2 = [n2.width, n2.height], a2 = [r2[1], r2[0]], s2 = (0, o.getGlsl)(this.context.glContext.version), u2 = `vec4 ${t2}(int index) {
      vec2 uv = packedUVfrom1D(
      ${a2[0]}, ${a2[1]}, index);
      return ${s2.texture2D}(${e2}, uv);
    }`;
              return new i2.GlslLibRoutine(u2, ["coordinates.packedUVfrom1D"]);
            }
            getPackedSampler2D(t2, e2, n2) {
              const a2 = n2.unpackedShape, s2 = [n2.width, n2.height], u2 = (0, o.getGlsl)(this.context.glContext.version), c = s2[0], l = s2[1];
              if (null != s2 && r.ArrayUtil.arraysEqual(a2, s2)) {
                const n3 = `vec4 ${t2}(int row, int col) {
        vec2 uv = (vec2(col, row) + halfCR) / vec2(${l}.0, ${c}.0);
        return ${u2.texture2D}(${e2}, uv);
      }`;
                return new i2.GlslLibRoutine(n3);
              }
              const p = s2, f = Math.ceil(a2[1] / 2), d = `vec4 ${t2}(int row, int col) {
      vec2 uv = packedUVfrom2D(${p[1]}, ${p[0]}, ${f}, row, col);
      return ${u2.texture2D}(${e2}, uv);
    }`;
              return new i2.GlslLibRoutine(d, ["coordinates.packedUVfrom2D"]);
            }
            getPackedSampler3D(t2, e2, n2) {
              const r2 = n2.unpackedShape, a2 = [n2.width, n2.height], u2 = [a2[0], a2[1]], c = (0, o.getGlsl)(this.context.glContext.version);
              if (1 === r2[0]) {
                const o2 = r2.slice(1), a3 = [1, 2], u3 = (0, s.squeezeInputShape)(r2, o2), c2 = ["b", "row", "col"], l2 = JSON.parse(JSON.stringify(n2));
                l2.unpackedShape = u3;
                const p2 = this.getPackedSamplerFromInput(t2, e2, l2), f2 = `${p2.routineBody}
      vec4 ${t2}(int b, int row, int col) {
        return ${t2}(${(0, s.getSqueezedParams)(c2, a3)});
      } `;
                return new i2.GlslLibRoutine(f2, p2.dependencies);
              }
              const l = u2[0], p = u2[1], f = Math.ceil(r2[2] / 2), d = `vec4 ${t2}(int b, int row, int col) {
      vec2 uv = packedUVfrom3D(
        ${p}, ${l}, ${f * Math.ceil(r2[1] / 2)}, ${f}, b, row, col);
      return ${c.texture2D}(${e2}, uv);}`;
              return new i2.GlslLibRoutine(d, ["coordinates.packedUVfrom3D"]);
            }
            getPackedSamplerND(t2, e2, n2) {
              const r2 = n2.unpackedShape, a2 = r2.length, s2 = [n2.width, n2.height], u2 = (0, o.getGlsl)(this.context.glContext.version), c = [s2[0], s2[1]], l = c[1], p = c[0], f = Math.ceil(r2[a2 - 1] / 2);
              let d = f * Math.ceil(r2[a2 - 2] / 2), h = "int b, int row, int col", g = `b * ${d} + (row / 2) * ${f} + (col / 2)`;
              for (let t3 = 2; t3 < a2 - 1; t3++) h = `int b${t3}, ` + h, d *= r2[a2 - t3 - 1], g = `b${t3} * ${d} + ` + g;
              const b = `vec4 ${t2}(${h}) {
      int index = ${g};
      int texR = index / ${p};
      int texC = index - texR * ${p};
      vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${p}, ${l});
      return ${u2.texture2D}(${e2}, uv);
    }`;
              return new i2.GlslLibRoutine(b);
            }
            getUnpackedSamplerScalar(t2, e2, n2) {
              const [r2, o2] = [n2.width, n2.height];
              if (1 === r2 && 1 === o2) {
                const n3 = `
          float ${t2}() {
            return sampleTexture(${e2}, halfCR);
          }
        `;
                return new i2.GlslLibRoutine(n3, ["coordinates.sampleTexture"]);
              }
              const a2 = `
        float ${t2}() {
          int offset_${e2} = coordsToOffset(TexCoords, ${r2}, ${o2});
          vec2 uv = uvFromFlat(${r2}, ${o2}, offset_${e2});
          return sampleTexture(${e2}, uv);
        }
      `;
              return new i2.GlslLibRoutine(a2, ["coordinates.uvFromFlat", "coordinates.sampleTexture", "coordinates.coordsToOffset"]);
            }
            getUnpackedSampler1D(t2, e2, n2) {
              const r2 = n2.width, o2 = n2.height;
              if (1 === o2 && 1 === r2) {
                const n3 = `
        float ${t2}(int index) {
          return sampleTexture(${e2}, halfCR);
        }
      `;
                return new i2.GlslLibRoutine(n3, ["coordinates.sampleTexture"]);
              }
              if (1 === o2) {
                const n3 = `
          float ${t2}(int index) {
            vec2 uv = vec2((float(index) + 0.5) / ${r2}.0, 0.5);
            return sampleTexture(${e2}, uv);
          }
        `;
                return new i2.GlslLibRoutine(n3, ["coordinates.sampleTexture"]);
              }
              if (1 === r2) {
                const n3 = `
          float ${t2}(int index) {
            vec2 uv = vec2(0.5, (float(index) + 0.5) / ${o2}.0);
            return sampleTexture(${e2}, uv);
          }
        `;
                return new i2.GlslLibRoutine(n3, ["coordinates.sampleTexture"]);
              }
              const a2 = `
        float ${t2}(int index) {
          vec2 uv = uvFromFlat(${r2}, ${o2}, index);
          return sampleTexture(${e2}, uv);
        }
      `;
              return new i2.GlslLibRoutine(a2, ["coordinates.uvFromFlat", "coordinates.sampleTexture"]);
            }
            getUnpackedSampler2D(t2, e2, n2) {
              const o2 = n2.unpackedShape, u2 = [n2.height, n2.width];
              if (null != u2 && r.ArrayUtil.arraysEqual(o2, u2)) {
                const n3 = `
          float ${t2}(int row, int col) {
            vec2 uv = (vec2(row, col) + halfCR) / vec2(${u2[1]}.0, ${u2[0]}.0);
            return sampleTexture(${e2}, uv);
          }
        `;
                return new i2.GlslLibRoutine(n3, ["coordinates.sampleTexture"]);
              }
              const { newShape: c, keptDims: l } = (0, a.squeezeShape)(o2), p = c;
              if (p.length < o2.length) {
                const r2 = (0, s.squeezeInputShape)(o2, p), a2 = JSON.parse(JSON.stringify(n2));
                a2.unpackedShape = r2;
                const u3 = ["col", "row"], c2 = `
          ${this.getUnpackedSamplerFromInput(t2, e2, a2).routineBody}
          float ${t2}(int row, int col) {
            return ${t2}(${(0, s.getSqueezedParams)(u3, l)});
          }
        `;
                return new i2.GlslLibRoutine(c2, ["coordinates.sampleTexture"]);
              }
              const f = u2[1], d = u2[0];
              if (1 === d) {
                const n3 = `
          float ${t2}(int row, int col) {
            int offset_${e2} = coordsToOffset(TexCoords, ${f}, ${d});
            float index = dot(vec3(row, col, offset_${e2}), vec3(${o2[1]}, 1, 1));
            vec2 uv = vec2(0.5, (index + 0.5) / ${f}.0);
            return sampleTexture(${e2}, uv);
          }
        `;
                return new i2.GlslLibRoutine(n3, ["coordinates.sampleTexture", "coordinates.coordsToOffset"]);
              }
              if (1 === f) {
                const n3 = `
          float ${t2}(int row, int col) {
            int offset_${e2} = coordsToOffset(TexCoords, ${f}, ${d});
            float index = dot(vec3(row, col, offset_${e2}), vec3(${o2[1]}, 1, 1));
            vec2 uv = vec2((index + 0.5) / ${d}.0, 0.5);
            return sampleTexture(${e2}, uv);
          }
        `;
                return new i2.GlslLibRoutine(n3, ["coordinates.sampleTexture", "coordinates.coordsToOffset"]);
              }
              const h = `
        float ${t2}(int row, int col) {
          int index = col * ${o2[1]} + row;
          vec2 uv = uvFromFlat(${f}, ${d}, index);
          return sampleTexture(${e2}, uv);
        }
      `;
              return new i2.GlslLibRoutine(h, ["coordinates.uvFromFlat", "coordinates.sampleTexture", "coordinates.coordsToOffset"]);
            }
            getUnpackedSampler3D(t2, e2, n2) {
              const r2 = n2.unpackedShape, o2 = r2[1] * r2[2], u2 = r2[2], { newShape: c, keptDims: l } = (0, a.squeezeShape)(r2), p = c;
              if (p.length < r2.length) {
                const o3 = (0, s.squeezeInputShape)(r2, p), a2 = ["batch", "col", "row"], u3 = JSON.parse(JSON.stringify(n2));
                u3.unpackedShape = o3;
                const c2 = this.getUnpackedSamplerFromInput(t2, e2, u3), f2 = l.reverse(), d = `
          ${c2.routineBody}
          float ${t2}(int batch, int row, int col) {
            return ${t2}(${(0, s.getSqueezedParams)(a2, f2)});
          }
        `;
                return new i2.GlslLibRoutine(d, c2.dependencies);
              }
              const f = `
          float ${t2}(int depth, int row, int col) {
            // Explicitly use integer operations as dot() only works on floats.
            int index = depth * ${o2} + col * ${u2} + row;
            vec2 uv = uvFromFlat(${n2.width}, ${n2.height}, index);
            return sampleTexture(${e2}, uv);
          }
      `;
              return new i2.GlslLibRoutine(f, ["coordinates.uvFromFlat", "coordinates.sampleTexture", "coordinates.coordsToOffset"]);
            }
            getUnpackedSampler4D(t2, e2, n2) {
              const r2 = n2.unpackedShape, o2 = r2[3], a2 = r2[2] * o2, s2 = `
        float ${t2}(int row, int col, int depth, int depth2) {
          int index = row * ${r2[1] * a2} + col * ${a2} +
              depth2 * ${o2} + depth;
          vec2 uv = uvFromFlat(${n2.width}, ${n2.height}, index);
          return sampleTexture(${e2}, uv);
        }
      `;
              return new i2.GlslLibRoutine(s2, ["coordinates.uvFromFlat", "coordinates.sampleTexture"]);
            }
            getUnpackedSampler5D(t2, e2, n2) {
              const r2 = n2.unpackedShape, o2 = r2[4], u2 = r2[3] * o2, c = r2[2] * u2, l = r2[1] * c, { newShape: p, keptDims: f } = (0, a.squeezeShape)(r2);
              if (p.length < r2.length) {
                const o3 = (0, s.squeezeInputShape)(r2, p), a2 = ["row", "col", "depth", "depth2", "depth3"], u3 = JSON.parse(JSON.stringify(n2));
                u3.unpackedShape = o3;
                const c2 = `
          ${this.getUnpackedSamplerFromInput(t2, e2, u3).routineBody}
          float ${t2}(int row, int col, int depth, int depth2, int depth3) {
            return ${t2}(${(0, s.getSqueezedParams)(a2, f)});
          }
        `;
                return new i2.GlslLibRoutine(c2, ["coordinates.sampleTexture", "coordinates.uvFromFlat"]);
              }
              const d = `
        float ${t2}(int row, int col, int depth, int depth2, int depth3) {
          int index = row * ${l} + col * ${c} + depth * ${u2} +
          depth3 * ${o2} + depth2;
          vec2 uv = uvFromFlat(${n2.width}, ${n2.height}, index);
          return sampleTexture(${e2}, uv);
        }
      `;
              return new i2.GlslLibRoutine(d, ["coordinates.sampleTexture", "coordinates.uvFromFlat"]);
            }
            getUnpackedSampler6D(t2, e2, n2) {
              const r2 = n2.unpackedShape, o2 = r2[5], u2 = r2[4] * o2, c = r2[3] * u2, l = r2[2] * c, p = r2[1] * l, { newShape: f, keptDims: d } = (0, a.squeezeShape)(r2);
              if (f.length < r2.length) {
                const o3 = (0, s.squeezeInputShape)(r2, f), a2 = ["row", "col", "depth", "depth2", "depth3", "depth4"], u3 = JSON.parse(JSON.stringify(n2));
                u3.unpackedShape = o3;
                const c2 = `
            ${this.getUnpackedSamplerFromInput(t2, e2, u3).routineBody}
            float ${t2}(int row, int col, int depth,
              int depth2, int depth3, int depth4) {
              return ${t2}(${(0, s.getSqueezedParams)(a2, d)});
            }
          `;
                return new i2.GlslLibRoutine(c2, ["coordinates.sampleTexture", "coordinates.uvFromFlat"]);
              }
              const h = `
          float ${t2}(int row, int col, int depth,
            int depth2, int depth3, int depth4) {
            int index = row * ${p} + col * ${l} + depth * ${c} +
            depth2 * ${u2} + depth3 * ${o2} + depth4;
            vec2 uv = uvFromFlat(${n2.width}, ${n2.height}, index);
            return sampleTexture(${e2}, uv);
          }
        `;
              return new i2.GlslLibRoutine(h, ["coordinates.uvFromFlat", "coordinates.sampleTexture", "coordinates.coordsToOffset"]);
            }
            toVec() {
              const t2 = this.context.outputTextureLayout, e2 = t2.shape.length, n2 = t2.strides, r2 = t2.width, o2 = t2.height, a2 = [];
              for (let t3 = 0; t3 < e2 - 1; ++t3) a2.push(`
        c[${t3}] = offset / ${n2[t3]};`), a2.push(`
        offset -= c[${t3}] * ${n2[t3]};`);
              a2.push(`
        c[${e2 - 1}] = offset;`);
              const s2 = `
      void toVec(vec2 texCoords, out int c[${e2}]) {
        int offset = coordsToOffset(texCoords, ${r2}, ${o2});
        ${a2.join("")}
      }
      void toVec(int offset, out int c[${e2}]) {
        ${a2.join("")}
      }
    `;
              return { toVec: new i2.GlslLibRoutine(s2, ["coordinates.coordsToOffset"]) };
            }
            valueFrom() {
              const t2 = {};
              return this.context.programInfo.inputNames.forEach(((e2, n2) => {
                const r2 = this.context.inputTextureLayouts[n2], o2 = (r2.unpackedShape.length > 0 ? r2.unpackedShape : r2.shape).length;
                let a2 = `_${e2}`;
                t2[a2] = new i2.GlslLibRoutine(this.getValueFromSingle(e2, o2, r2.width, r2.height, false), [`shapeUtils.indicesToOffset${a2}`, "coordinates.offsetToCoords", "fragcolor.getColorAsFloat"]), a2 += "_T", t2[a2] = new i2.GlslLibRoutine(this.getValueFromSingle(e2, o2, r2.width, r2.height, true), [`shapeUtils.indicesToOffset${a2}`, "coordinates.offsetToCoords", "fragcolor.getColorAsFloat"]);
              })), t2;
            }
            getValueFromSingle(t2, e2, n2, r2, i3) {
              let a2 = `_${t2}`;
              return i3 && (a2 += "_T"), `
        float ${a2}(int m[${e2}]) {
          int offset = indicesToOffset${a2}(m);
          vec2 coords = offsetToCoords(offset, ${n2}, ${r2});
          float value = getColorAsFloat(${(0, o.getGlsl)(this.context.glContext.version).texture2D}(${t2}, coords));
          return value;
        }
        `;
            }
            getPackedValueFrom(t2, e2, n2, r2, i3) {
              let a2 = `_${t2}_Pack`;
              return i3 && (a2 += "_T"), `
        vec4 ${a2}(int m[${e2}]) {
          int offset = indicesToOffset_${t2}(m);
          vec2 coords = offsetToCoords(offset, ${n2}, ${r2});
          return ${(0, o.getGlsl)(this.context.glContext.version).texture2D}(${t2}, coords);
        }
        `;
            }
          }
          e.CoordsGlslLib = u;
        }, 8520: (t, e) => {
          var n;
          Object.defineProperty(e, "__esModule", { value: true }), e.TopologicalSortGlslRoutines = e.GlslLibRoutineNode = e.GlslLibRoutine = e.GlslLib = e.GlslContext = e.FunctionType = void 0, (n = e.FunctionType || (e.FunctionType = {}))[n.ValueBased = 0] = "ValueBased", n[n.Positional = 1] = "Positional", e.GlslContext = class {
            constructor(t2, e2, n2, r) {
              this.glContext = t2, this.programInfo = e2, this.inputTextureLayouts = n2, this.outputTextureLayout = r;
            }
          }, e.GlslLib = class {
            constructor(t2) {
              this.context = t2;
            }
          }, e.GlslLibRoutine = class {
            constructor(t2, e2) {
              this.routineBody = t2, this.dependencies = e2;
            }
          }, e.GlslLibRoutineNode = class {
            constructor(t2, e2, n2) {
              this.name = t2, this.dependencies = n2 || [], e2 && (this.routineBody = e2);
            }
            addDependency(t2) {
              t2 && this.dependencies.push(t2);
            }
          }, e.TopologicalSortGlslRoutines = class {
            static returnOrderedNodes(t2) {
              if (!t2 || 0 === t2.length) return [];
              if (1 === t2.length) return t2;
              const e2 = /* @__PURE__ */ new Set(), n2 = /* @__PURE__ */ new Set(), r = new Array();
              return this.createOrderedNodes(t2, e2, n2, r), r;
            }
            static createOrderedNodes(t2, e2, n2, r) {
              for (let i2 = 0; i2 < t2.length; ++i2) this.dfsTraverse(t2[i2], e2, n2, r);
            }
            static dfsTraverse(t2, e2, n2, r) {
              if (!t2 || n2.has(t2.name)) return;
              if (e2.has(t2.name)) throw new Error("Cyclic dependency detected. Can't topologically sort routines needed for shader.");
              e2.add(t2.name);
              const i2 = t2.dependencies;
              if (i2 && i2.length > 0) for (let t3 = 0; t3 < i2.length; ++t3) this.dfsTraverse(i2[t3], e2, n2, r);
              r.push(t2), n2.add(t2.name), e2.delete(t2.name);
            }
          };
        }, 7341: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.EncodingGlslLib = void 0;
          const r = n(8520);
          class i2 extends r.GlslLib {
            constructor(t2) {
              super(t2);
            }
            getFunctions() {
              return Object.assign(Object.assign({}, this.encodeFloat32()), this.decodeFloat32());
            }
            getCustomTypes() {
              return {};
            }
            encodeFloat32() {
              return { encode: new r.GlslLibRoutine("highp vec4 encode(highp float f) {\n        return vec4(f, 0.0, 0.0, 0.0);\n      }\n        ") };
            }
            decodeFloat32() {
              return { decode: new r.GlslLibRoutine("highp float decode(highp vec4 rgba) {\n        return rgba.r;\n      }\n        ") };
            }
            encodeUint8() {
              const t2 = i2.isLittleEndian() ? "rgba.rgba=rgba.abgr;" : "";
              return { encode: new r.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)));
        ${t2}
        rgba = rgba / 255.0; // values need to be normalized to [0,1]
        return rgba;
    }
        `) };
            }
            decodeUint8() {
              const t2 = i2.isLittleEndian() ? "rgba.rgba=rgba.abgr;" : "";
              return { decode: new r.GlslLibRoutine(`
        highp float decode(highp vec4 rgba) {
          rgba = rgba * 255.0; // values need to be de-normalized from [0,1] to [0,255]
          ${t2}
          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;
      }
        `) };
            }
            static isLittleEndian() {
              const t2 = new ArrayBuffer(4), e2 = new Uint32Array(t2), n2 = new Uint8Array(t2);
              if (e2[0] = 3735928559, 239 === n2[0]) return true;
              if (222 === n2[0]) return false;
              throw new Error("unknown endianness");
            }
          }
          e.EncodingGlslLib = i2;
        }, 9894: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.FragColorGlslLib = void 0;
          const r = n(8520), i2 = n(5060);
          class o extends r.GlslLib {
            constructor(t2) {
              super(t2);
            }
            getFunctions() {
              return Object.assign(Object.assign({}, this.setFragColor()), this.getColorAsFloat());
            }
            getCustomTypes() {
              return {};
            }
            setFragColor() {
              const t2 = (0, i2.getGlsl)(this.context.glContext.version);
              return { setFragColor: new r.GlslLibRoutine(`
        void setFragColor(float value) {
            ${t2.output} = encode(value);
        }
        `, ["encoding.encode"]) };
            }
            getColorAsFloat() {
              return { getColorAsFloat: new r.GlslLibRoutine("\n        float getColorAsFloat(vec4 color) {\n            return decode(color);\n        }\n        ", ["encoding.decode"]) };
            }
          }
          e.FragColorGlslLib = o;
        }, 2848: (t, e) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.replaceInlines = void 0;
          const n = /@inline[\s\n\r]+(\w+)[\s\n\r]+([0-9a-zA-Z_]+)\s*\(([^)]*)\)\s*{(([^}]|[\n\r])*)}/gm;
          e.replaceInlines = function(t2) {
            const e2 = {};
            let r;
            for (; null !== (r = n.exec(t2)); ) {
              const t3 = r[3].split(",").map(((t4) => {
                const e3 = t4.trim().split(" ");
                return e3 && 2 === e3.length ? { type: e3[0], name: e3[1] } : null;
              })).filter(((t4) => null !== t4));
              e2[r[2]] = { params: t3, body: r[4] };
            }
            for (const n2 in e2) {
              const i2 = "(\\w+)?\\s+([_0-9a-zA-Z]+)\\s+=\\s+__FUNC__\\((.*)\\)\\s*;".replace("__FUNC__", n2), o = new RegExp(i2, "gm");
              for (; null !== (r = o.exec(t2)); ) {
                const i3 = r[1], o2 = r[2], a = r[3].split(","), s = i3 ? `${i3} ${o2};` : "";
                let u = e2[n2].body, c = "";
                e2[n2].params.forEach(((t3, e3) => {
                  t3 && (c += `${t3.type} ${t3.name} = ${a[e3]};
`);
                })), u = `${c}
 ${u}`, u = u.replace("return", `${o2} = `);
                const l = `
      ${s}
      {
        ${u}
      }
      `;
                t2 = t2.replace(r[0], l);
              }
            }
            return t2.replace(n, "");
          };
        }, 8879: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.GlslPreprocessor = void 0;
          const r = n(8520), i2 = n(2848), o = n(5483), a = n(5060);
          e.GlslPreprocessor = class {
            constructor(t2, e2, n2, i3) {
              this.libs = {}, this.glslLibRoutineDependencyGraph = {}, this.context = new r.GlslContext(t2, e2, n2, i3), Object.keys(o.glslRegistry).forEach(((t3) => {
                const e3 = new o.glslRegistry[t3](this.context);
                this.libs[t3] = e3;
              }));
              const a2 = this.glslLibRoutineDependencyGraph;
              for (const t3 in this.libs) {
                const e3 = this.libs[t3].getFunctions();
                for (const n3 in e3) {
                  const i4 = t3 + "." + n3;
                  let o2;
                  a2[i4] ? (o2 = a2[i4], o2.routineBody = e3[n3].routineBody) : (o2 = new r.GlslLibRoutineNode(i4, e3[n3].routineBody), a2[i4] = o2);
                  const s = e3[n3].dependencies;
                  if (s) for (let t4 = 0; t4 < s.length; ++t4) if (a2[s[t4]]) o2.addDependency(a2[s[t4]]);
                  else {
                    const e4 = new r.GlslLibRoutineNode(s[t4]);
                    a2[s[t4]] = e4, o2.addDependency(e4);
                  }
                }
              }
            }
            preprocess() {
              const t2 = this.context.programInfo;
              let e2 = t2.shaderSource;
              return this.context.programInfo.hasMain || (e2 = `${e2}
      ${(0, a.getDefaultFragShaderMain)(this.context.glContext.version, this.context.outputTextureLayout.shape.length)}`), e2 = (0, i2.replaceInlines)(e2), `${(0, a.getFragShaderPreamble)(this.context.glContext.version)}
    ${this.getUniforms(t2.inputNames, t2.variables)}
    ${this.getImports(e2)}
    ${e2}`;
            }
            getImports(t2) {
              const e2 = this.selectGlslLibRoutinesToBeIncluded(t2);
              if (0 === e2.length) return "";
              let n2 = "";
              for (let t3 = 0; t3 < e2.length; ++t3) {
                if (!e2[t3].routineBody) throw new Error(`Missing body for the Glsl Library routine: ${e2[t3].name}`);
                n2 += e2[t3].routineBody + "\n";
              }
              return n2;
            }
            selectGlslLibRoutinesToBeIncluded(t2) {
              const e2 = [];
              return Object.keys(this.glslLibRoutineDependencyGraph).forEach(((n2) => {
                const r2 = n2.split(".")[1];
                -1 !== t2.indexOf(r2) && e2.push(this.glslLibRoutineDependencyGraph[n2]);
              })), r.TopologicalSortGlslRoutines.returnOrderedNodes(e2);
            }
            getUniforms(t2, e2) {
              const n2 = [];
              if (t2) for (const e3 of t2) n2.push(`uniform sampler2D ${e3};`);
              if (e2) for (const t3 of e2) n2.push(`uniform ${t3.type} ${t3.name}${t3.arrayLength ? `[${t3.arrayLength}]` : ""};`);
              return n2.join("\n");
            }
          };
        }, 5483: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.glslRegistry = void 0;
          const r = n(5107), i2 = n(7341), o = n(9894), a = n(2655), s = n(3891);
          e.glslRegistry = { encoding: i2.EncodingGlslLib, fragcolor: o.FragColorGlslLib, vec: s.VecGlslLib, shapeUtils: a.ShapeUtilsGlslLib, coordinates: r.CoordsGlslLib };
        }, 2655: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.ShapeUtilsGlslLib = void 0;
          const r = n(8520);
          class i2 extends r.GlslLib {
            constructor(t2) {
              super(t2);
            }
            getFunctions() {
              return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, this.bcastIndex()), this.bcastMatmulIndex()), this.offsetToIndices()), this.indicesToOffset()), this.incrementIndices());
            }
            getCustomTypes() {
              return {};
            }
            bcastIndex() {
              const t2 = this.context.outputTextureLayout.shape.length, e2 = {};
              return this.context.programInfo.inputNames.forEach(((n2, i3) => {
                const o = this.context.inputTextureLayouts[i3].unpackedShape;
                if (o.length <= t2) {
                  const i4 = o.length, a = t2 - i4, s = `bcastIndices_${n2}`;
                  let u = "";
                  for (let t3 = 0; t3 < i4; ++t3) u += `
          realIndices[${t3}] = int( mod(float(bcastedIndices[${a + t3}]), ${o[t3]}.0) );
          `;
                  const c = `
        void ${s} (int bcastedIndices[${t2}], out int realIndices[${i4}]) {
          ${u}
        }
        `;
                  e2[s] = new r.GlslLibRoutine(c);
                }
              })), e2;
            }
            bcastMatmulIndex() {
              const t2 = this.context.outputTextureLayout.shape.length, e2 = {};
              return this.context.programInfo.inputNames.forEach(((n2, i3) => {
                const o = this.context.inputTextureLayouts[i3].shape;
                if (!(o.length < 2 || o.length > t2)) {
                  const i4 = o.length, a = t2 - i4, s = `bcastMatmulIndices_${n2}`;
                  let u = "";
                  for (let t3 = 0; t3 < i4 - 2; ++t3) u += `
          realIndices[${t3}] = int( mod(float(bcastedIndices[${a + t3}]), ${o[t3]}.0) );
          `;
                  const c = `
        void ${s}(int bcastedIndices[${t2}], out int realIndices[${i4}]) {
          ${u}
          realIndices[${i4 - 1}] = bcastedIndices[${t2 - 1}];
          realIndices[${i4 - 2}] = bcastedIndices[${t2 - 2}];
        }
        `;
                  e2[s] = new r.GlslLibRoutine(c);
                }
              })), e2;
            }
            indicesToOffset() {
              const t2 = {};
              return this.context.programInfo.inputNames.forEach(((e2, n2) => {
                const o = this.context.inputTextureLayouts[n2].shape, a = this.context.inputTextureLayouts[n2].strides, s = o.length;
                let u = `indicesToOffset_${e2}`;
                t2[u] = new r.GlslLibRoutine(i2.indexToOffsetSingle(u, s, a)), u = `indicesToOffset_${e2}_T`, t2[u] = new r.GlslLibRoutine(i2.indexToOffsetSingle(u, s, a.slice().reverse()));
              })), t2;
            }
            static indexToOffsetSingle(t2, e2, n2) {
              let r2 = "";
              for (let t3 = e2 - 1; t3 >= 0; --t3) r2 += `
        offset += indices[${t3}] * ${n2[t3]};
        `;
              return `
      int ${t2}(int indices[${e2}]) {
        int offset = 0;
        ${r2}
        return offset;
      }
      `;
            }
            offsetToIndices() {
              const t2 = {};
              return this.context.programInfo.inputNames.forEach(((e2, n2) => {
                const o = this.context.inputTextureLayouts[n2].shape, a = this.context.inputTextureLayouts[n2].strides, s = o.length;
                let u = `offsetToIndices_${e2}`;
                t2[u] = new r.GlslLibRoutine(i2.offsetToIndicesSingle(u, s, a)), u = `offsetToIndices_${e2}_T`, t2[u] = new r.GlslLibRoutine(i2.offsetToIndicesSingle(u, s, a.slice().reverse()));
              })), t2;
            }
            static offsetToIndicesSingle(t2, e2, n2) {
              const r2 = [];
              for (let t3 = 0; t3 < e2 - 1; ++t3) r2.push(`
      indices[${t3}] = offset / ${n2[t3]};`), r2.push(`
        offset -= indices[${t3}] * ${n2[t3]};`);
              return r2.push(`
      indices[${e2 - 1}] = offset;`), `
      void ${t2}(int offset, out int indices[${e2}]) {
        ${r2.join("")}
      }
      `;
            }
            incrementIndices() {
              const t2 = {};
              return this.context.programInfo.inputNames.forEach(((e2, n2) => {
                const i3 = this.context.inputTextureLayouts[n2].shape, o = i3.length, a = `incrementIndices_${e2}`;
                let s = "";
                for (let t3 = 0; t3 < o; ++t3) s += `
        shape[${t3}] = ${i3[t3]};`;
                const u = `
        void ${a}(int axis, out int indices[${o}]) {
          int shape[${o}];
          ${s};
          for(int i = ${o} -1 ; i >= 0; --i) {
            if(i > axis) continue;
            indices[i] += 1;
            if(indices[i] < shape[i]) {
              break;
            }
            indices[i] = 0;
          }
        }
        `;
                t2[a] = new r.GlslLibRoutine(u);
              })), t2;
            }
          }
          e.ShapeUtilsGlslLib = i2;
        }, 5060: (t, e) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.getDefaultFragShaderMain = e.getFragShaderPreamble = e.getVertexShaderSource = e.getGlsl = void 0;
          const n = { version: "", attribute: "attribute", varyingVertex: "varying", varyingFrag: "varying", texture2D: "texture2D", output: "gl_FragColor", outputDeclaration: "" }, r = { version: "#version 300 es", attribute: "in", varyingVertex: "out", varyingFrag: "in", texture2D: "texture", output: "outputColor", outputDeclaration: "out vec4 outputColor;" };
          function i2(t2) {
            return 1 === t2 ? n : r;
          }
          e.getGlsl = i2, e.getVertexShaderSource = function(t2) {
            const e2 = i2(t2);
            return `${e2.version}
      precision highp float;
      ${e2.attribute} vec3 position;
      ${e2.attribute} vec2 textureCoord;

      ${e2.varyingVertex} vec2 TexCoords;

      void main()
      {
          gl_Position = vec4(position, 1.0);
          TexCoords = textureCoord;
      }`;
          }, e.getFragShaderPreamble = function(t2) {
            const e2 = i2(t2);
            return `${e2.version}
    precision highp float;
    precision highp int;
    precision highp sampler2D;
    ${e2.varyingFrag} vec2 TexCoords;
    ${e2.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);
    }

    `;
          }, e.getDefaultFragShaderMain = function(t2, e2) {
            return `
  void main() {
    int indices[${e2}];
    toVec(TexCoords, indices);
    vec4 result = vec4(process(indices));
    ${i2(t2).output} = result;
  }
  `;
          };
        }, 3891: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.VecGlslLib = void 0;
          const r = n(8520);
          class i2 extends r.GlslLib {
            constructor(t2) {
              super(t2);
            }
            getCustomTypes() {
              return {};
            }
            getFunctions() {
              return Object.assign(Object.assign(Object.assign(Object.assign({}, this.binaryVecFunctions()), this.copyVec()), this.setVecItem()), this.getVecItem());
            }
            binaryVecFunctions() {
              const t2 = this.context.outputTextureLayout.shape.length, e2 = { add: "+=", sub: "-=", mul: "*=", div: "/=" }, n2 = {};
              for (const i3 in e2) {
                const o = `${i3}Vec`;
                let a = "";
                for (let n3 = 0; n3 < t2; ++n3) a += `
          dest[${n3}] ${e2[i3]} src[${n3}];
          `;
                const s = `
        void ${o}(int src[${t2}], out int dest[${t2}]) {
          ${a}
        }
        `;
                n2[o] = new r.GlslLibRoutine(s);
              }
              return n2;
            }
            copyVec() {
              const t2 = this.context.outputTextureLayout.shape.length;
              let e2 = "";
              for (let n3 = 0; n3 < t2; ++n3) e2 += `
        dest[${n3}] = src[${n3}];
        `;
              const n2 = `
      void copyVec(int src[${t2}], out int dest[${t2}]) {
        ${e2}
      }
      `;
              return { copyVec: new r.GlslLibRoutine(n2) };
            }
            setVecItem() {
              const t2 = this.context.outputTextureLayout.shape.length;
              let e2 = `
        if(index < 0)
            index =${t2} + index;
        if (index == 0)
            m[0] = value;
        `;
              for (let n3 = 1; n3 < t2 - 1; ++n3) e2 += `
        else if (index == ${n3})
            m[${n3}] = value;
            `;
              e2 += `
        else
            m[${t2 - 1}] = value;
        `;
              const n2 = `
      void setVecItem(out int m[${t2}], int index, int value) {
        ${e2}
      }
        `;
              return { setVecItem: new r.GlslLibRoutine(n2) };
            }
            getVecItem() {
              const t2 = this.context.outputTextureLayout.shape.length;
              let e2 = `
        if(index < 0)
            index = ${t2} + index;
        if (index == 0)
            return m[0];
      `;
              for (let n3 = 1; n3 < t2 - 1; ++n3) e2 += `
        else if (index == ${n3})
            return m[${n3}];
      `;
              e2 += `
        else
            return m[${t2 - 1}];
        `;
              const n2 = `
      int getVecItem(int m[${t2}], int index) {
        ${e2}
      }
    `;
              return { getVecItem: new r.GlslLibRoutine(n2) };
            }
          }
          e.VecGlslLib = i2;
        }, 8316: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.WebGLInferenceHandler = void 0;
          const r = n(6231), i2 = n(9162), o = n(2517), a = n(2403), s = n(7019), u = n(8710), c = n(5611), l = n(4057), p = n(2039);
          e.WebGLInferenceHandler = class {
            constructor(t2) {
              this.session = t2, this.packedTextureDataCache = /* @__PURE__ */ new Map(), this.unpackedTextureDataCache = /* @__PURE__ */ new Map();
            }
            calculateTextureWidthAndHeight(t2, e2) {
              return (0, l.calculateTextureWidthAndHeight)(this.session.layoutStrategy, t2, e2);
            }
            executeProgram(t2, e2) {
              if (e2.length < t2.inputNames.length) throw new Error(`Input size mustn't be less than ${t2.inputNames.length}.`);
              if (t2.inputNames.length !== t2.inputTypes.length) throw new Error("input names size does not match input types");
              const n2 = [];
              for (let r3 = 0; r3 < t2.inputNames.length; ++r3) n2[r3] = this.getOrCreateTextureData(e2[r3], t2.inputTypes[r3]);
              const r2 = ((t3, e3) => {
                const n3 = e3.map(((t4) => `${t4.unpackedShape.join(",")};${t4.width}x${t4.height}`)).join("_");
                let r3 = t3.name;
                return t3.cacheHint && (r3 += "[" + t3.cacheHint + "]"), r3 += ":" + n3, r3;
              })(t2, n2);
              let i3 = this.session.programManager.getArtifact(r2);
              const o2 = i3 ? i3.programInfo : "function" == typeof t2.get ? t2.get() : t2, a2 = (0, l.createTextureLayoutFromTextureType)(this.session.layoutStrategy, o2.output.dims, o2.output.textureType), s2 = this.createTextureData(a2, o2.output.type);
              return i3 || (i3 = this.session.programManager.build(o2, n2, s2), this.session.programManager.setArtifact(r2, i3)), this.runProgram(i3, n2, s2), s2;
            }
            run(t2, e2) {
              return this.executeProgram(t2, e2).tensor;
            }
            runProgram(t2, e2, n2) {
              for (let n3 = 0; n3 < e2.length; ++n3) if (!!e2[n3].isPacked != (t2.programInfo.inputTypes[n3] === p.TextureType.packed)) throw new Error(`input[${n3}] property packed inconsistent`);
              if (!!n2.isPacked != (t2.programInfo.output.textureType === p.TextureType.packed)) throw new Error("output property packed inconsistent");
              this.session.programManager.run(t2, e2, n2);
            }
            getOrCreateTextureData(t2, e2) {
              let n2 = this.getTextureData(t2.dataId, e2 === p.TextureType.packed);
              if (!n2 && (n2 = this.getTextureData(t2.dataId, e2 !== p.TextureType.packed), n2)) return e2 === p.TextureType.packed ? this.pack(n2) : this.unpack(n2);
              if (!n2) {
                const r2 = (0, l.createTextureLayoutFromTextureType)(this.session.layoutStrategy, t2.dims, e2);
                if (e2 === p.TextureType.packedLastDimension) {
                  const n3 = 1, r3 = 4, i3 = t2.dims;
                  if (4 === i3.length) {
                    const o2 = [i3[0], Math.ceil(i3[1] * i3[2] * i3[3] / r3)], a2 = (0, l.createTextureLayoutFromTextureType)(this.session.layoutStrategy, o2, e2);
                    let s2 = t2.numberData;
                    if (i3[1] * i3[2] * i3[3] % r3 != 0) {
                      const e3 = i3[0], o3 = i3[1] * i3[2] * i3[3], a3 = Math.ceil(o3 * n3 / r3) * r3;
                      s2 = new Float32Array(e3 * a3);
                      for (let r4 = 0; r4 < e3; ++r4) {
                        const e4 = r4 * o3, i4 = r4 * a3 + r4 % n3 * o3;
                        s2.set(t2.numberData.subarray(e4, e4 + o3), i4);
                      }
                    }
                    return this.createTextureData(a2, t2.type, s2, t2, 1);
                  }
                }
                if (e2 === p.TextureType.packed) {
                  const e3 = (0, l.createTextureLayoutFromShape)(this.session.layoutStrategy, t2.dims, 1, [], { reverseWH: true }), r3 = this.createTextureData(e3, t2.type, t2.numberData, t2, 1);
                  n2 = this.pack(r3);
                } else n2 = this.createTextureData(r2, t2.type, t2.numberData, t2, 1);
              }
              return n2;
            }
            createTextureDataFromLayoutBindTensor(t2, e2, n2, r2) {
              return this.createTextureData(t2, e2, n2, r2, 1);
            }
            createTextureData(t2, e2, n2, i3, o2) {
              r.Logger.verbose("InferenceHandler", `Creating TextureData: layout:[${JSON.stringify(t2)}]`);
              const a2 = this.session.textureManager.createTextureFromLayout(e2, t2, n2, o2);
              return this.createTextureDataFromTexture(t2, e2, a2, i3);
            }
            reshapeUnpacked(t2, e2) {
              const n2 = this.getOrCreateTextureData(t2, p.TextureType.unpacked), r2 = { channels: n2.channels, height: n2.height, width: n2.width, shape: 0 !== e2.length ? e2 : [1], strides: o.ShapeUtil.computeStrides(e2), unpackedShape: e2 };
              return this.createTextureDataFromTexture(r2, t2.type, n2.texture).tensor;
            }
            reshapePacked(t2, e2) {
              const n2 = this.getOrCreateTextureData(t2, p.TextureType.packed);
              if ((0, s.isReshapeCheap)(t2.dims, e2)) {
                const r3 = { channels: n2.channels, height: n2.height, width: n2.width, shape: 0 !== e2.length ? e2 : [1], strides: o.ShapeUtil.computeStrides(e2), unpackedShape: e2, isPacked: true };
                return this.createTextureDataFromTexture(r3, t2.type, n2.texture).tensor;
              }
              const r2 = (0, s.processDims3D)(t2.dims), i3 = (0, s.processDims3D)(e2), a2 = this.reshapePacked(t2, r2), u2 = this.run((0, s.createPackedReshape3DProgramInfoLoader)(this, a2, i3), [a2]);
              return this.reshapePacked(u2, e2);
            }
            cast(t2, e2) {
              const n2 = this.getOrCreateTextureData(t2, p.TextureType.unpacked);
              return this.createTextureDataFromTexture(n2, e2, n2.texture).tensor;
            }
            createTextureDataFromTexture(t2, e2, n2, r2, o2) {
              const a2 = Object.assign(Object.assign({}, t2), { tensor: r2 || new i2.Tensor(t2.unpackedShape, e2, ((t3) => this.readTexture(a2)), ((t3) => __async(this, null, function* () {
                return this.readTextureAsync(a2);
              })), void 0, o2), texture: n2 });
              return this.setTextureData(a2.tensor.dataId, a2, t2.isPacked), a2;
            }
            getTextureData(t2, e2 = false) {
              return this.session.isInitializer(t2) ? this.session.getTextureData(t2, e2) : e2 ? this.packedTextureDataCache.get(t2) : this.unpackedTextureDataCache.get(t2);
            }
            setTextureData(t2, e2, n2 = false) {
              this.session.isInitializer(t2) ? this.session.setTextureData(t2, e2, n2) : (n2 ? this.packedTextureDataCache : this.unpackedTextureDataCache).set(t2, e2);
            }
            isTextureLayoutCached(t2, e2 = false) {
              return !!this.getTextureData(t2.dataId, e2);
            }
            dispose() {
              this.session.textureManager.clearActiveTextures(), this.packedTextureDataCache.forEach(((t2) => this.session.textureManager.releaseTexture(t2))), this.packedTextureDataCache = /* @__PURE__ */ new Map(), this.unpackedTextureDataCache.forEach(((t2) => this.session.textureManager.releaseTexture(t2))), this.unpackedTextureDataCache = /* @__PURE__ */ new Map();
            }
            readTexture(t2) {
              return t2.isPacked ? this.readTexture(this.unpack(t2)) : this.session.backend.glContext.isFloat32DownloadSupported ? this.session.textureManager.readTexture(t2, t2.tensor.type, t2.channels) : this.session.textureManager.readUint8TextureAsFloat((0, u.encodeAsUint8)(this, t2));
            }
            readTextureAsync(t2) {
              return __async(this, null, function* () {
                return t2.isPacked ? this.readTextureAsync(this.unpack(t2)) : this.session.backend.glContext.isFloat32DownloadSupported ? this.session.textureManager.readTextureAsync(t2, t2.tensor.type, t2.channels) : this.session.textureManager.readUint8TextureAsFloat((0, u.encodeAsUint8)(this, t2));
              });
            }
            pack(t2) {
              return this.executeProgram((0, a.createPackProgramInfoLoader)(this, t2.tensor), [t2.tensor]);
            }
            unpack(t2) {
              return this.executeProgram((0, c.createUnpackProgramInfoLoader)(this, t2.tensor), [t2.tensor]);
            }
          };
        }, 1640: function(t, e, n) {
          var r = this && this.__createBinding || (Object.create ? function(t2, e2, n2, r2) {
            void 0 === r2 && (r2 = n2);
            var i3 = Object.getOwnPropertyDescriptor(e2, n2);
            i3 && !("get" in i3 ? !e2.__esModule : i3.writable || i3.configurable) || (i3 = { enumerable: true, get: function() {
              return e2[n2];
            } }), Object.defineProperty(t2, r2, i3);
          } : function(t2, e2, n2, r2) {
            void 0 === r2 && (r2 = n2), t2[r2] = e2[n2];
          }), i2 = this && this.__setModuleDefault || (Object.create ? function(t2, e2) {
            Object.defineProperty(t2, "default", { enumerable: true, value: e2 });
          } : function(t2, e2) {
            t2.default = e2;
          }), o = this && this.__importStar || function(t2) {
            if (t2 && t2.__esModule) return t2;
            var e2 = {};
            if (null != t2) for (var n2 in t2) "default" !== n2 && Object.prototype.hasOwnProperty.call(t2, n2) && r(e2, t2, n2);
            return i2(e2, t2), e2;
          };
          Object.defineProperty(e, "__esModule", { value: true }), e.WEBGL_OP_RESOLVE_RULES = void 0;
          const a = n(2898), s = o(n(7839)), u = n(4196), c = n(2069), l = n(8138), p = n(9663), f = n(5193), d = n(7992), h = n(1253), g = n(4776), b = n(6572), m = n(3346), y = n(5623), _ = n(2870), v = n(2143), w = n(4939), x = n(718), T = n(2268), S = n(8117), O = n(2278), A = n(5524), E = n(5975), I = n(3933), P = n(6558), D = n(5723), $ = n(3738), k = o(n(4909)), C = n(8428), F = n(9793);
          e.WEBGL_OP_RESOLVE_RULES = [["Abs", "", "6+", k.abs], ["Acos", "", "7+", k.acos], ["Add", "", "7+", s.add], ["And", "", "7+", s.and], ["Asin", "", "7+", k.asin], ["Atan", "", "7+", k.atan], ["AveragePool", "", "7+", v.averagePool, v.parseAveragePoolAttributes], ["BatchNormalization", "", "7+", a.batchNormalization, a.parseBatchNormalizationAttributes], ["Cast", "", "6+", u.cast, u.parseCastAttributes], ["Ceil", "", "6+", k.ceil], ["Clip", "", "6-10", k.clip, k.parseClipAttributes], ["Clip", "", "11+", k.clipV11], ["Concat", "", "4+", c.concat, c.parseConcatAttributes], ["Conv", "", "1+", l.conv, l.parseConvAttributes], ["ConvTranspose", "", "1+", p.convTranspose, p.parseConvTransposeAttributes], ["Cos", "", "7+", k.cos], ["Div", "", "7+", s.div], ["Dropout", "", "7+", k.identity], ["DepthToSpace", "", "1+", f.depthToSpace, f.parseDepthToSpaceAttributes], ["Equal", "", "7+", s.equal], ["Elu", "", "6+", k.elu, k.parseEluAttributes], ["Exp", "", "6+", k.exp], ["Flatten", "", "1+", d.flatten, d.parseFlattenAttributes], ["Floor", "", "6+", k.floor], ["FusedConv", "com.microsoft", "1+", l.conv, l.parseConvAttributes], ["Gather", "", "1+", h.gather, h.parseGatherAttributes], ["Gemm", "", "7-10", g.gemm, g.parseGemmAttributesV7], ["Gemm", "", "11+", g.gemm, g.parseGemmAttributesV11], ["GlobalAveragePool", "", "1+", v.globalAveragePool, v.parseGlobalAveragePoolAttributes], ["GlobalMaxPool", "", "1+", v.globalMaxPool], ["Greater", "", "7+", s.greater], ["Identity", "", "1+", k.identity], ["ImageScaler", "", "1+", b.imageScaler, b.parseImageScalerAttributes], ["InstanceNormalization", "", "6+", m.instanceNormalization, m.parseInstanceNormalizationAttributes], ["LeakyRelu", "", "6+", k.leakyRelu, k.parseLeakyReluAttributes], ["Less", "", "7+", s.less], ["Log", "", "6+", k.log], ["MatMul", "", "1+", y.matMul, y.parseMatMulAttributes], ["MaxPool", "", "1+", v.maxPool, v.parseMaxPoolAttributes], ["Mul", "", "7+", s.mul], ["Neg", "", "6+", k.neg], ["Not", "", "1+", k.not], ["Or", "", "7+", s.or], ["Pad", "", "2-10", _.padV2, _.parsePadAttributesV2], ["Pad", "", "11+", _.padV11, _.parsePadAttributesV11], ["Pow", "", "7+", s.pow], ["PRelu", "", "7+", s.pRelu], ["ReduceLogSum", "", "1+", w.reduceLogSum, w.parseReduceAttributes], ["ReduceMax", "", "1+", w.reduceMax, w.parseReduceAttributes], ["ReduceMean", "", "1+", w.reduceMean, w.parseReduceAttributes], ["ReduceMin", "", "1+", w.reduceMin, w.parseReduceAttributes], ["ReduceProd", "", "1+", w.reduceProd, w.parseReduceAttributes], ["ReduceSum", "", "1-12", w.reduceSum, w.parseReduceAttributes], ["ReduceSumSquare", "", "1+", w.reduceLogSumSquare, w.parseReduceAttributes], ["Relu", "", "6+", k.relu], ["Reshape", "", "5+", x.reshape], ["Resize", "", "10", T.resize, T.parseResizeAttributesV10], ["Resize", "", "11+", T.resize, T.parseResizeAttributesV11], ["Shape", "", "1+", S.shape], ["Sigmoid", "", "6+", k.sigmoid], ["Sin", "", "7+", k.sin], ["Slice", "", "10+", O.sliceV10], ["Slice", "", "1-9", O.slice, O.parseSliceAttributes], ["Softmax", "", "1-12", A.softmax, A.parseSoftmaxAttributes], ["Softmax", "", "13+", A.softmaxV13, A.parseSoftmaxAttributesV13], ["Split", "", "2-12", E.split, E.parseSplitAttributes], ["Sqrt", "", "6+", k.sqrt], ["Squeeze", "", "1-12", I.squeeze, I.parseSqueezeAttributes], ["Squeeze", "", "13+", I.squeezeV13], ["Sub", "", "7+", s.sub], ["Sum", "", "6+", P.sum], ["Tan", "", "7+", k.tan], ["Tanh", "", "6+", k.tanh], ["Tile", "", "6+", D.tile], ["Transpose", "", "1+", $.transpose, $.parseTransposeAttributes], ["Upsample", "", "7-8", F.upsample, F.parseUpsampleAttributesV7], ["Upsample", "", "9", F.upsample, F.parseUpsampleAttributesV9], ["Unsqueeze", "", "1-12", C.unsqueeze, C.parseUnsqueezeAttributes], ["Unsqueeze", "", "13+", C.unsqueezeV13], ["Xor", "", "7+", s.xor]];
        }, 2898: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.parseBatchNormalizationAttributes = e.batchNormalization = void 0;
          const r = n(246), i2 = n(5060), o = n(2039), a = { name: "BatchNormalization", inputNames: ["A", "Scale", "B", "Mean", "Variance"], inputTypes: [o.TextureType.unpacked, o.TextureType.unpacked, o.TextureType.unpacked, o.TextureType.unpacked, o.TextureType.unpacked] };
          e.batchNormalization = (t2, e2, n2) => (u(e2), [t2.run(Object.assign(Object.assign({}, a), { cacheHint: n2.cacheKey, get: () => s(t2, e2, n2) }), e2)]), e.parseBatchNormalizationAttributes = (t2) => {
            const e2 = t2.attributes.getFloat("epsilon", 1e-5), n2 = t2.attributes.getFloat("momentum", 0.9), i3 = t2.attributes.getInt("spatial", 1);
            return (0, r.createAttributeWithCacheKey)({ epsilon: e2, momentum: n2, spatial: i3 });
          };
          const s = (t2, e2, n2) => {
            const r2 = (0, i2.getGlsl)(t2.session.backend.glContext.version), s2 = e2[0].dims.length, [u2, c] = t2.calculateTextureWidthAndHeight(e2[1].dims, o.TextureType.unpacked), l = `
  float process(int[${s2}] indices) {
    vec2 position = offsetToCoords(indices[1], ${u2}, ${c});
    float scale = getColorAsFloat(${r2.texture2D}(Scale, position));
    float mean = getColorAsFloat(${r2.texture2D}(Mean, position));
    float variance = getColorAsFloat(${r2.texture2D}(Variance, position));
    float b = getColorAsFloat(${r2.texture2D}(B, position));

    return scale * ( (_A(indices) - mean) / sqrt(variance + float(${n2.epsilon})) ) + b;
  }`;
            return Object.assign(Object.assign({}, a), { output: { dims: e2[0].dims, type: e2[0].type, textureType: o.TextureType.unpacked }, shaderSource: l });
          }, u = (t2) => {
            if (!t2 || 5 !== t2.length) throw new Error("BatchNormalization requires 5 inputs.");
            const e2 = t2[0], n2 = t2[1], r2 = t2[2], i3 = t2[3], o2 = t2[4];
            if (e2.dims.length < 3 || 1 !== n2.dims.length || 1 !== r2.dims.length || 1 !== i3.dims.length || 1 !== o2.dims.length) throw new Error("invalid input shape.");
            if (n2.dims[0] !== e2.dims[1] || r2.dims[0] !== e2.dims[1] || i3.dims[0] !== e2.dims[1] || o2.dims[0] !== e2.dims[1]) throw new Error("invalid input shape.");
            if ("float32" !== e2.type && "float64" !== e2.type || "float32" !== n2.type && "float64" !== n2.type || "float32" !== r2.type && "float64" !== r2.type || "float32" !== i3.type && "float64" !== i3.type || "float32" !== o2.type && "float64" !== o2.type) throw new Error("invalid input tensor types.");
          };
        }, 7839: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.xor = e.sub = e.pRelu = e.pow = e.or = e.mul = e.less = e.greater = e.equal = e.div = e.and = e.add = e.glslPRelu = e.glslPow = e.glslXor = e.glslOr = e.glslAnd = e.glslLess = e.glslGreater = e.glslEqual = e.glslSub = e.glslMul = e.glslDiv = e.glslAdd = void 0;
          const r = n(2517), i2 = n(8520), o = n(5060), a = n(2039);
          function s() {
            const t2 = "add_";
            return { body: `
  float ${t2}(float a, float b) {
    return a + b;
  }
  vec4 ${t2}(vec4 v1, vec4 v2) {
    return v1 + v2;
  }
  `, name: t2, type: i2.FunctionType.ValueBased };
          }
          function u() {
            const t2 = "div_";
            return { body: `
  float ${t2}(float a, float b) {
    return a / b;
  }
  vec4 ${t2}(vec4 v1, vec4 v2) {
    return v1 / v2;
  }
  `, name: t2, type: i2.FunctionType.ValueBased };
          }
          function c() {
            const t2 = "mul_";
            return { body: `
  float ${t2}(float a, float b) {
    return a * b;
  }
  vec4 ${t2}(vec4 v1, vec4 v2) {
    return v1 * v2;
  }
  `, name: t2, type: i2.FunctionType.ValueBased };
          }
          function l() {
            const t2 = "sub_";
            return { body: `
  float ${t2}(float a, float b) {
    return a - b;
  }
  vec4 ${t2}(vec4 v1, vec4 v2) {
    return v1 - v2;
  }
  `, name: t2, type: i2.FunctionType.ValueBased };
          }
          function p() {
            const t2 = "equal_";
            return { body: `
  float ${t2}(float a, float b) {
    return float(a == b);
  }
  vec4 ${t2}(vec4 v1, vec4 v2) {
    return vec4(equal(v1, v2));
  }
  `, name: t2, type: i2.FunctionType.ValueBased };
          }
          function f() {
            const t2 = "greater_";
            return { body: `
  float ${t2}(float a, float b) {
    return float(a > b);
  }
  vec4 ${t2}(vec4 v1, vec4 v2) {
    return vec4( v1.r > v2.r ,
      v1.g > v2.g,
      v1.b > v2.b,
      v1.a > v2.a );
  }
  `, name: t2, type: i2.FunctionType.ValueBased };
          }
          function d() {
            const t2 = "less_";
            return { body: `
  float ${t2}(float a, float b) {
    return float(a < b);
  }
  vec4 ${t2}(vec4 v1, vec4 v2) {
    return vec4( v1.r < v2.r ,
                v1.g < v2.g,
                v1.b < v2.b,
                v1.a < v2.a );
  }
  `, name: t2, type: i2.FunctionType.ValueBased };
          }
          function h() {
            const t2 = "and_";
            return { body: `
  float ${t2}(float a, float b) {
    return float( bool(a) && bool(b) );
  }
  vec4 ${t2}(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 );
  }
  `, name: t2, type: i2.FunctionType.ValueBased };
          }
          function g() {
            const t2 = "or_";
            return { body: `
  float ${t2}(float a, float b) {
    return float( bool(a) || bool(b) );
  }
  vec4 ${t2}(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 );
  }
  `, name: t2, type: i2.FunctionType.ValueBased };
          }
          function b() {
            const t2 = "xor_";
            return { body: `
  float ${t2}(float a, float b) {
    return float( bool(a) ^^ bool(b) );
  }
  vec4 ${t2}(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 );
  }
  `, name: t2, type: i2.FunctionType.ValueBased };
          }
          function m() {
            return (function(t2) {
              const e2 = `${t2}_`;
              return { body: `
  float ${e2}(float a, float b) {
    return ${t2}(a, b);
  }
  vec4 ${e2}(vec4 v1, vec4 v2) {
    return ${t2}(v1, v2);
  }
  `, name: e2, type: i2.FunctionType.ValueBased };
            })("pow");
          }
          function y() {
            const t2 = "prelu_";
            return { body: `
  float ${t2}(float a, float b) {
    return a < 0.0 ? a * b: a;
  }
  vec4 ${t2}(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
      );
  }
  `, name: t2, type: i2.FunctionType.ValueBased };
          }
          e.glslAdd = s, e.glslDiv = u, e.glslMul = c, e.glslSub = l, e.glslEqual = p, e.glslGreater = f, e.glslLess = d, e.glslAnd = h, e.glslOr = g, e.glslXor = b, e.glslPow = m, e.glslPRelu = y;
          const _ = (t2, e2, n2, r2 = e2[0].type, i3) => {
            const o2 = t2.session.pack ? a.TextureType.packed : a.TextureType.unpacked;
            return { name: n2.name, inputNames: ["A", "B"], inputTypes: [o2, o2], cacheHint: i3, get: () => v(t2, e2, n2, r2) };
          }, v = (t2, e2, n2, i3 = e2[0].type) => {
            const s2 = t2.session.pack ? a.TextureType.packed : a.TextureType.unpacked, u2 = !r.ShapeUtil.areEqual(e2[0].dims, e2[1].dims);
            let c2 = e2[0].dims;
            const l2 = t2.session.pack;
            if (u2) {
              const a2 = r.BroadcastUtil.calcShape(e2[0].dims, e2[1].dims, false);
              if (!a2) throw new Error("Can't perform binary op on the given tensors");
              c2 = a2;
              const u3 = c2.length, p3 = 0 !== e2[0].dims.length ? e2[0].dims.length : 1, f3 = 0 !== e2[1].dims.length ? e2[1].dims.length : 1, d2 = 0 !== e2[0].dims.length ? "bcastIndices_A(indices, aindices);" : "aindices[0] = 0;", h2 = 0 !== e2[1].dims.length ? "bcastIndices_B(indices, bindices);" : "bindices[0] = 0;", g2 = (0, o.getGlsl)(t2.session.backend.glContext.version), b2 = l2 ? `
      ${n2.body}
      void main() {
        vec4 a = getAAtOutCoords();
        vec4 b = getBAtOutCoords();
        vec4 result = ${n2.name}(a, b);
        ${g2.output} = result;
      }` : `
      ${n2.body}
      float process(int indices[${u3}]) {
        int aindices[${p3}];
        int bindices[${f3}];
        ${d2}
        ${h2}
        return ${n2.name}(_A(aindices), _B(bindices));
      }`;
              return { name: n2.name, inputNames: ["A", "B"], inputTypes: [s2, s2], output: { dims: c2, type: i3, textureType: s2 }, shaderSource: b2, hasMain: l2 };
            }
            const p2 = (0, o.getGlsl)(t2.session.backend.glContext.version), f2 = `
    ${n2.body}
    void main() {
      vec4 v1 = ${p2.texture2D}(A, TexCoords);
      vec4 v2 = ${p2.texture2D}(B, TexCoords);
      vec4 result = ${n2.name}(v1, v2);
      ${p2.output} = result;
    }
    `;
            return { name: n2.name, inputNames: ["A", "B"], inputTypes: [s2, s2], output: { dims: e2[0].dims, type: i3, textureType: s2 }, shaderSource: f2, hasMain: true };
          };
          e.add = (t2, e2) => [t2.run(_(t2, e2, s()), e2)], e.and = (t2, e2) => [t2.run(_(t2, e2, h(), "bool"), e2)], e.div = (t2, e2) => [t2.run(_(t2, e2, u()), e2)], e.equal = (t2, e2) => [t2.run(_(t2, e2, p(), "bool"), e2)], e.greater = (t2, e2) => [t2.run(_(t2, e2, f(), "bool"), e2)], e.less = (t2, e2) => [t2.run(_(t2, e2, d(), "bool"), e2)], e.mul = (t2, e2) => [t2.run(_(t2, e2, c()), e2)], e.or = (t2, e2) => [t2.run(_(t2, e2, g(), "bool"), e2)], e.pow = (t2, e2) => [t2.run(_(t2, e2, m()), e2)], e.pRelu = (t2, e2) => [t2.run(_(t2, e2, y()), e2)], e.sub = (t2, e2) => [t2.run(_(t2, e2, l()), e2)], e.xor = (t2, e2) => [t2.run(_(t2, e2, b(), "bool"), e2)];
        }, 4196: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.parseCastAttributes = e.cast = void 0;
          const r = n(2517);
          e.cast = (t2, e2, n2) => (i2(e2), [t2.cast(e2[0], n2)]), e.parseCastAttributes = (t2) => r.ProtoUtil.tensorDataTypeFromProto(t2.attributes.getInt("to"));
          const i2 = (t2) => {
            if (!t2 || 1 !== t2.length) throw new Error("Cast requires 1 input.");
            if ("string" === t2[0].type) throw new Error("Invalid input type.");
          };
        }, 1163: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.createPackedConcatProgramInfoLoader = void 0;
          const r = n(5060), i2 = n(2039), o = n(9390), a = n(2827);
          e.createPackedConcatProgramInfoLoader = (t2, e2, n2) => {
            const u = (c = e2.length, l = n2.cacheKey, { name: "Concat (packed)", inputNames: Array.from({ length: c }, ((t3, e3) => `X${e3}`)), inputTypes: Array(c).fill(i2.TextureType.packed), cacheHint: l });
            var c, l;
            return Object.assign(Object.assign({}, u), { get: () => ((t3, e3, n3, u2) => {
              const c2 = n3[0].dims.slice();
              if (u2 >= c2.length || u2 < -1 * c2.length) throw new Error("axis specified for concat doesn't match input dimensionality");
              u2 < 0 && (u2 = c2.length + u2);
              const l2 = c2.slice(0);
              for (let t4 = 1; t4 < n3.length; t4++) {
                const e4 = n3[t4].dims.slice();
                for (let t5 = 0; t5 < c2.length; t5++) if (t5 === u2) l2[u2] += e4[t5];
                else if (c2[t5] !== e4[t5]) throw new Error("non concat dimensions must match");
              }
              const p = l2.length, f = (0, a.getChannels)("coords", p), d = (0, o.getCoordsDataType)(p), h = (0, a.unpackFromChannel)(), g = n3.map(((t4) => t4.dims)), b = (0, o.getGlChannels)(p), m = new Array(g.length - 1);
              m[0] = g[0][u2];
              for (let t4 = 1; t4 < m.length; t4++) m[t4] = m[t4 - 1] + g[t4][u2];
              const y = b[u2], _ = b.slice(-2), v = b.join();
              let w = `if (${y} < ${m[0]}) {
        return getChannel(
            getX0(${v}), vec2(${_.join()}));
        }`;
              for (let t4 = 1; t4 < m.length; t4++) {
                const e4 = m[t4 - 1];
                w += `
            if (${y} < ${m[t4]}  && ${y} >= ${m[t4 - 1]}) {
              return getChannel(
                getX${t4}(${s(b, y, e4)}),
                vec2(${s(_, y, e4)}));
            }`;
              }
              const x = m.length, T = m[m.length - 1];
              w += `
            return getChannel(
              getX${x}(${s(b, y, T)}),
              vec2(${s(_, y, T)}));`;
              const S = (0, r.getGlsl)(t3.session.backend.glContext.version), O = `
          ${h}
          float getValue(${b.map(((t4) => "int " + t4))}) {
            ${w}
          }

          void main() {
            ${d} coords = getOutputCoords();
            int lastDim = coords.${b[p - 1]};
            coords.${b[p - 1]} = coords.${b[p - 2]};
            coords.${b[p - 2]} = lastDim;

            vec4 result = vec4(getValue(${f}), 0., 0., 0.);

            ${f[p - 1]} = ${f[p - 1]} + 1;
            if (${f[p - 1]} < ${l2[p - 1]}) {
              result.g = getValue(${f});
            }

            ${f[p - 2]} = ${f[p - 2]} + 1;
            if (${f[p - 2]} < ${l2[p - 2]}) {
              result.a = getValue(${f});
            }

            ${f[p - 1]} = ${f[p - 1]} - 1;
            if (${f[p - 2]} < ${l2[p - 2]} &&
                ${f[p - 1]} < ${l2[p - 1]}) {
              result.b = getValue(${f});
            }
            ${S.output} = result;
          }
        `;
              return Object.assign(Object.assign({}, e3), { output: { dims: l2, type: n3[0].type, textureType: i2.TextureType.packed }, shaderSource: O, hasMain: true });
            })(t2, u, e2, n2.axis) });
          };
          const s = (t2, e2, n2) => {
            const r2 = t2.indexOf(e2);
            return t2.map(((t3, e3) => e3 === r2 ? `${t3} - ${n2}` : t3)).join();
          };
        }, 2069: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.parseConcatAttributes = e.concat = void 0;
          const r = n(246), i2 = n(2039), o = n(1163);
          e.concat = (t2, e2, n2) => (p(e2), t2.session.pack && e2[0].dims.length > 1 ? [t2.run((0, o.createPackedConcatProgramInfoLoader)(t2, e2, n2), e2)] : [t2.run(a(t2, e2, n2), e2)]);
          const a = (t2, e2, n2) => {
            const r2 = (o2 = e2.length, a2 = n2.cacheKey, { name: "Concat", inputNames: Array.from({ length: o2 }, ((t3, e3) => `X${e3}`)), inputTypes: Array(o2).fill(i2.TextureType.unpacked), cacheHint: a2 });
            var o2, a2;
            return Object.assign(Object.assign({}, r2), { get: () => ((t3, e3, n3, r3) => {
              const o3 = n3[0].dims.slice();
              if (r3 >= o3.length || r3 < -1 * o3.length) throw new Error("axis specified for concat doesn't match input dimensionality");
              r3 < 0 && (r3 = o3.length + r3);
              const a3 = o3.slice(0);
              for (let t4 = 1; t4 < n3.length; t4++) {
                const e4 = n3[t4].dims.slice();
                for (let t5 = 0; t5 < o3.length; t5++) if (t5 === r3) a3[r3] += e4[t5];
                else if (o3[t5] !== e4[t5]) throw new Error("non concat dimensions must match");
              }
              const p2 = a3.length, f = new Array(n3.length);
              let d = 0;
              for (let t4 = 0; t4 < f.length; ++t4) d += n3[t4].dims[r3], f[t4] = d;
              let h = "";
              h = n3.length < 5 ? s(f) : u(f);
              const g = `
        ${c(n3.length, p2)}
        ${l(f)}
        ${h}
        float process(int indices[${p2}]) {
          int textureIndex = getTextureWhereDataResides (indices[${r3}]);

          if(textureIndex != 0) {
            indices[${r3}] = indices[${r3}] - int(getSizeInConcatAxisValueFromIndex(textureIndex-int(1)));
          }

          return fetchDataFromCorrectTexture(textureIndex, indices);
        }`;
              return Object.assign(Object.assign({}, e3), { output: { dims: a3, type: n3[0].type, textureType: i2.TextureType.unpacked }, shaderSource: g });
            })(0, r2, e2, n2.axis) });
          }, s = (t2) => `int getTextureWhereDataResides(int index) {
      ${t2.map(((t3, e2) => `if(index<${t3}) {return ${e2};}
`)).join("")}
    }`, u = (t2) => s(t2), c = (t2, e2) => {
            const n2 = [`float fetchDataFromCorrectTexture(int textureIndex, int indices[${e2}]) {`];
            for (let e3 = 0; e3 < t2; ++e3) 0 === e3 ? n2.push(`	if (textureIndex == ${e3}) { return _X${e3}(indices); }`) : e3 === t2 - 1 ? n2.push(`	else { return _X${e3}(indices); }`) : n2.push(`	else if (textureIndex == ${e3}) { return _X${e3}(indices); }`);
            return n2.push("	}"), n2.join("\n");
          }, l = (t2) => {
            const e2 = ["int getSizeInConcatAxisValueFromIndex(int index) {"];
            for (let n2 = 0; n2 < t2.length; ++n2) 0 === n2 ? e2.push(`	if (index == ${n2}) { return ${t2[n2]}; }`) : n2 === t2.length - 1 ? e2.push(`	else { return ${t2[n2]}; }`) : e2.push(`	else if (index == ${n2}) { return ${t2[n2]}; }`);
            return e2.push("	}"), e2.join("\n");
          };
          e.parseConcatAttributes = (t2) => (0, r.createAttributeWithCacheKey)({ axis: t2.attributes.getInt("axis") });
          const p = (t2) => {
            if (!t2 || t2.length < 1) throw new Error("too few inputs");
            const e2 = t2[0].type, n2 = t2[0].dims.length;
            if ("string" === e2) throw new Error("string tensor is not supported yet");
            for (const r2 of t2) {
              if (r2.type !== e2) throw new Error("input tensors should be one type");
              if (r2.dims.length !== n2) throw new Error("input tensors should have the same shape");
            }
          };
        }, 4770: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.createUnpackedGroupedConvProgramInfoLoader = void 0;
          const r = n(6231), i2 = n(5060), o = n(2039), a = n(8138), s = n(2823);
          e.createUnpackedGroupedConvProgramInfoLoader = (t2, e2, n2) => {
            const u = (c = e2.length > 2, l = n2.cacheKey, { name: "GroupedConv", inputNames: c ? ["X", "W", "Bias"] : ["X", "W"], inputTypes: c ? [o.TextureType.unpacked, o.TextureType.unpacked, o.TextureType.unpacked] : [o.TextureType.unpacked, o.TextureType.unpacked], cacheHint: l });
            var c, l;
            return Object.assign(Object.assign({}, u), { get: () => ((t3, e3, n3, u2) => {
              const c2 = e3.length > 2 ? "value += getBias(output_channel);" : "", l2 = e3[0].dims.slice(), p = e3[1].dims.slice(), f = p[0] / u2.group;
              r.Logger.verbose("GroupedConv", `autpPad:${u2.autoPad}, dilations:${u2.dilations}, group:${u2.group}, kernelShape:${u2.kernelShape}, pads:${u2.pads}, strides:${u2.strides}`);
              const d = (0, a.calculateOutputShape)(l2, p, u2.dilations, u2.pads, u2.strides), h = (0, i2.getGlsl)(t3.session.backend.glContext.version), { activationFunction: g, applyActivation: b } = (0, s.getActivationSnippet)(u2), m = `
  const ivec2 strides = ivec2(${u2.strides[0]}, ${u2.strides[1]});
  const ivec2 pads = ivec2(${u2.pads[0]}, ${u2.pads[1]});
  ${g}
  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 / ${f};

    float value = 0.0;
    for (int wInChannel = 0; wInChannel < ${p[1]}; wInChannel++) {
      int input_channel = group_id * ${p[1]} + wInChannel;
      for (int wHeight = 0; wHeight < ${p[2]}; wHeight++) {
        int xHeight = xRCCorner.x + wHeight * ${u2.dilations[0]};

        if (xHeight < 0 || xHeight >= ${l2[2]}) {
          continue;
        }

        for (int wWidth = 0; wWidth < ${p[3]}; wWidth++) {
          int xWidth = xRCCorner.y + wWidth * ${u2.dilations[1]};
          if (xWidth < 0 || xWidth >= ${l2[3]}) {
            continue;
          }

          float xVal = getX(batch, input_channel, xWidth, xHeight);
          float wVal = getW(output_channel, wInChannel, wWidth, wHeight);
          value += xVal*wVal;
        }
      }
    }
    ${c2}
    ${b}
    ${h.output} = vec4(value, .0, .0, .0);
  }
`;
              return Object.assign(Object.assign({}, n3), { output: { dims: d, type: e3[0].type, textureType: o.TextureType.unpacked }, shaderSource: m, hasMain: true });
            })(t2, e2, u, n2) });
          };
        }, 1386: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.conv2DPacked = e.conv2DPackedPointwise = void 0;
          const r = n(8138), i2 = n(8555), o = n(708);
          e.conv2DPackedPointwise = (t2, e2, n2) => {
            const i3 = e2[0].dims, a = e2[1].dims, s = (0, r.calculateOutputShape)(i3, a, n2.dilations, n2.pads, n2.strides), u = t2.reshapePacked(e2[0], [i3[1], i3[2] * i3[3]]), c = t2.reshapePacked(e2[1], [a[0], a[1]]), l = e2.length > 2 ? [c, u, e2[2]] : [c, u], p = t2.run((0, o.createPackedMatmulProgramInfoLoader)(t2, l, n2), l);
            return t2.reshapePacked(p, s);
          }, e.conv2DPacked = (t2, e2, n2) => {
            const a = e2[0].dims, s = e2[1].dims, u = (0, r.calculateOutputShape)(a, s, n2.dilations, n2.pads, n2.strides), c = t2.run((0, i2.createPackedIm2ColProgramInfoLoader)(t2, e2[0], e2[1], u, n2), [e2[0]]), l = t2.reshapePacked(e2[1], [s[0], s[1] * s[2] * s[3]]), p = 3 === e2.length ? [l, c, e2[2]] : [l, c], f = t2.run((0, o.createPackedMatmulProgramInfoLoader)(t2, p, n2), p);
            return t2.reshapePacked(f, u);
          };
        }, 9663: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.parseConvTransposeAttributes = e.convTranspose = void 0;
          const r = n(246), i2 = n(5060), o = n(2039), a = n(2823), s = (t2, e2, n2, r2, i3, o2) => (t2 - 1) * e2 + n2 + (r2 - 1) * i3 + 1 - o2, u = (t2, e2, n2, r2, i3) => {
            const o2 = Math.floor(t2 / 2);
            "SAME_UPPER" === e2 ? (n2[r2] = o2, n2[i3] = t2 - o2) : "SAME_LOWER" === e2 && (n2[r2] = t2 - o2, n2[i3] = o2);
          };
          e.convTranspose = (t2, e2, n2) => (f(e2, n2), c(t2, e2, n2));
          const c = (t2, e2, n2) => {
            const r2 = p(n2, e2);
            return [l(t2, e2, r2)];
          }, l = (t2, e2, n2) => t2.run(((t3, e3, n3) => {
            const r2 = (s2 = e3.length > 2, u2 = n3.cacheKey, { name: "ConvTranspose", inputNames: s2 ? ["X", "W", "B"] : ["X", "W"], inputTypes: s2 ? [o.TextureType.unpacked, o.TextureType.unpacked, o.TextureType.unpacked] : [o.TextureType.unpacked, o.TextureType.unpacked], cacheHint: u2 });
            var s2, u2;
            return Object.assign(Object.assign({}, r2), { get: () => ((t4, e4, n4, r3) => {
              const s3 = e4.length > 2 ? "getB(output_channel)" : "0.0", u3 = e4[0].dims, c2 = e4[1].dims, l2 = c2[1], p2 = c2[0] / r3.group, f2 = [e4[0].dims[0], e4[1].dims[1] * r3.group, ...r3.outputShape], d = (0, i2.getGlsl)(t4.session.backend.glContext.version), { activationFunction: h, applyActivation: g } = (0, a.getActivationSnippet)(r3), b = `
  const ivec2 strides = ivec2(${r3.strides[0]}, ${r3.strides[1]});
  const ivec2 pads = ivec2(${r3.pads[0]}, ${r3.pads[1]});
  ${h}
  void main() {
    ivec4 coords = getOutputCoords();
    int batch = coords.x;
    int output_channel = coords.y;

    ivec2 loc = coords.zw + pads;

    int group_id = output_channel / ${l2};
    int wOutChannel = output_channel - group_id * ${l2};

    float value = ${s3};
    for (int inChannelOffset = 0; inChannelOffset < ${p2}; inChannelOffset++) {
      int input_channel = group_id * ${p2} + inChannelOffset;
      for (int wWOff = 0; wWOff < ${c2[2]}; wWOff++) {
        for (int wHOff = 0; wHOff < ${c2[3]}; wHOff++) {
          ivec2 wOff = ivec2(wWOff * ${r3.dilations[0]}, wHOff * ${r3.dilations[1]});
          ivec2 wLoc = loc - wOff;
          ivec2 wLocIn = wLoc / strides;
          if (
            wLocIn * strides == wLoc &&
            wLocIn.x >= 0 && wLocIn.x < ${u3[2]} &&
            wLocIn.y >= 0 && wLocIn.y < ${u3[3]}
          ) {
            float xVal = getX(batch, input_channel, wLocIn.y, wLocIn.x);
            float wVal = getW(input_channel, wOutChannel, wHOff, wWOff);
            value += xVal * wVal;
          }
        }
      }
    }
    ${g}
    ${d.output} = vec4(value, .0, .0, .0);
  }
`;
              return Object.assign(Object.assign({}, n4), { output: { dims: f2, type: e4[0].type, textureType: o.TextureType.unpacked }, shaderSource: b, hasMain: true });
            })(t3, e3, r2, n3) });
          })(t2, e2, n2), e2), p = (t2, e2) => {
            const n2 = t2.kernelShape.slice();
            if (0 === t2.kernelShape.length) for (let t3 = 2; t3 < e2[1].dims.length; ++t3) n2.push(e2[1].dims[t3]);
            const r2 = t2.pads.slice(), i3 = t2.outputShape.slice();
            ((t3, e3, n3, r3, i4, o3, a2, c2) => {
              const l2 = t3.length - 2, p2 = 0 === c2.length;
              for (let f2 = 0; f2 < l2; ++f2) {
                const d = p2 ? t3[f2 + 2] * o3[f2] : c2[f2], h = s(t3[f2 + 2], o3[f2], i4[f2], e3[f2], n3[f2], d);
                u(h, r3, i4, f2, f2 + l2), p2 && c2.push(o3[f2] * (t3[f2 + 2] - 1) + a2[f2] + (e3[f2] - 1) * n3[f2] + 1 - i4[f2] - i4[f2 + l2]);
              }
            })(e2[0].dims, n2, t2.dilations, t2.autoPad, r2, t2.strides, t2.outputPadding, i3);
            const o2 = Object.assign({}, t2);
            return Object.assign(o2, { kernelShape: n2, pads: r2, outputShape: i3, cacheKey: t2.cacheKey }), o2;
          };
          e.parseConvTransposeAttributes = (t2) => {
            const e2 = t2.attributes, n2 = (0, a.parseInternalActivationAttributes)(e2), i3 = e2.getString("auto_pad", "NOTSET"), o2 = e2.getInts("dilations", [1, 1]), s2 = e2.getInt("group", 1), u2 = e2.getInts("kernel_shape", []), c2 = e2.getInts("output_padding", [0, 0]), l2 = e2.getInts("output_shape", []), p2 = e2.getInts("pads", [0, 0, 0, 0]), f2 = e2.getInts("strides", [1, 1]);
            return (0, r.createAttributeWithCacheKey)(Object.assign({ autoPad: i3, dilations: o2, group: s2, kernelShape: u2, outputPadding: c2, outputShape: l2, pads: p2, strides: f2 }, n2));
          };
          const f = (t2, e2) => {
            if (!t2 || 2 !== t2.length && 3 !== t2.length) throw new Error("Conv requires 2 or 3 inputs");
            if (4 !== t2[0].dims.length || 4 !== t2[1].dims.length) throw new Error("currently only support 2-dimensional conv");
            if (t2[0].dims[1] !== t2[1].dims[0]) throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");
            const n2 = t2[1].dims[1] * e2.group;
            if (3 === t2.length && (1 !== t2[2].dims.length || t2[2].dims[0] !== n2)) throw new Error("invalid bias");
            const r2 = t2[0].dims.length - 2;
            if (e2.dilations.length !== r2) throw new Error(`dilations should be ${r2}D`);
            if (e2.strides.length !== r2) throw new Error(`strides should be ${r2}D`);
            if (e2.pads.length !== 2 * r2) throw new Error(`pads should be ${2 * r2}D`);
            if (e2.outputPadding.length !== r2) throw new Error(`output_padding should be ${r2}D`);
            if (0 !== e2.kernelShape.length && e2.kernelShape.length !== t2[1].dims.length - 2) throw new Error("invalid kernel shape");
            if (0 !== e2.outputShape.length && e2.outputShape.length !== t2[0].dims.length - 2) throw new Error("invalid output shape");
            if ("float32" !== t2[0].type || "float32" !== t2[1].type) throw new Error("ConvTranspose input(X,W) should be float tensor");
            if (3 === t2.length && "float32" !== t2[2].type) throw new Error("ConvTranspose input(bias) should be float tensor");
          };
        }, 8138: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.parseConvAttributes = e.conv = e.calculateOutputShape = void 0;
          const r = n(246), i2 = n(2517), o = n(4770), a = n(1386), s = n(9828), u = n(2823), c = n(3248), l = n(5623);
          e.calculateOutputShape = (t2, e2, n2, r2, i3) => {
            const o2 = t2[0], a2 = t2.slice(2), s2 = a2.length, u2 = e2[0], c2 = e2.slice(2).map(((t3, e3) => t3 + (t3 - 1) * (n2[e3] - 1))), l2 = a2.map(((t3, e3) => t3 + r2[e3] + r2[e3 + s2])).map(((t3, e3) => Math.floor((t3 - c2[e3] + i3[e3]) / i3[e3])));
            return [o2, u2].concat(...l2);
          }, e.conv = (t2, e2, n2) => (g(e2, n2), p(t2, e2, n2));
          const p = (t2, e2, n2) => {
            const r2 = h(n2, e2), i3 = t2.session.pack, s2 = 1 === r2.kernelShape[0] && 1 === r2.kernelShape[1];
            return r2.group > 1 ? [t2.run((0, o.createUnpackedGroupedConvProgramInfoLoader)(t2, e2, r2), e2)] : s2 && i3 ? [f(t2, e2, r2)] : i3 && 4 === e2[0].dims.length && 1 === e2[0].dims[0] && !s2 ? [(0, a.conv2DPacked)(t2, e2, r2)] : [d(t2, e2, r2)];
          }, f = (t2, n2, r2) => {
            const i3 = n2[0].dims, o2 = n2[1].dims, a2 = (0, e.calculateOutputShape)(i3, o2, r2.dilations, r2.pads, r2.strides), s2 = t2.reshapeUnpacked(n2[0], [i3[1], i3[2] * i3[3]]), u2 = t2.reshapeUnpacked(n2[1], [o2[0], o2[1]]), c2 = n2.length > 2 ? [u2, s2, n2[2]] : [u2, s2], p2 = t2.run((0, l.createMatmulProgramInfoLoader)(c2, r2), c2);
            return t2.reshapeUnpacked(p2, a2);
          }, d = (t2, n2, r2) => {
            const i3 = n2[0].dims, o2 = n2[1].dims, a2 = (0, e.calculateOutputShape)(i3, o2, r2.dilations, r2.pads, r2.strides), u2 = t2.run((0, c.createIm2ColProgramInfoLoader)(t2, n2[0], n2[1], a2, r2), [n2[0]]), l2 = 3 === n2.length ? [u2, n2[1], n2[2]] : [u2, n2[1]];
            return t2.run((0, s.createDotProductProgramInfoLoader)(t2, n2, a2, r2), l2);
          }, h = (t2, e2) => {
            const n2 = t2.kernelShape.slice();
            if (0 === t2.kernelShape.length) for (let t3 = 2; t3 < e2[1].dims.length; ++t3) n2.push(e2[1].dims[t3]);
            const r2 = t2.pads.slice();
            i2.PoolConvUtil.adjustPadsBasedOnAutoPad(e2[0].dims, t2.strides, t2.dilations, n2, r2, t2.autoPad);
            const o2 = Object.assign({}, t2);
            return Object.assign(o2, { kernelShape: n2, pads: r2, cacheKey: t2.cacheKey }), o2;
          };
          e.parseConvAttributes = (t2) => {
            const e2 = t2.attributes, n2 = (0, u.parseInternalActivationAttributes)(e2), i3 = e2.getString("auto_pad", "NOTSET"), o2 = e2.getInts("dilations", [1, 1]), a2 = e2.getInt("group", 1), s2 = e2.getInts("kernel_shape", []), c2 = e2.getInts("pads", [0, 0, 0, 0]), l2 = e2.getInts("strides", [1, 1]);
            return (0, r.createAttributeWithCacheKey)(Object.assign({ autoPad: i3, dilations: o2, group: a2, kernelShape: s2, pads: c2, strides: l2 }, n2));
          };
          const g = (t2, e2) => {
            if (!t2 || 2 !== t2.length && 3 !== t2.length) throw new Error("Conv requires 2 or 3 inputs");
            if (4 !== t2[0].dims.length || 4 !== t2[1].dims.length) throw new Error("currently only support 2-dimensional conv");
            if (t2[0].dims[1] !== t2[1].dims[1] * e2.group) throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");
            if (3 === t2.length && (1 !== t2[2].dims.length || t2[1].dims[0] !== t2[2].dims[0])) throw new Error("invalid bias");
            const n2 = t2[0].dims.length - 2;
            if (e2.dilations.length !== n2) throw new Error(`dilations should be ${n2}D`);
            if (e2.strides.length !== n2) throw new Error(`strides should be ${n2}D`);
            if (e2.pads.length !== 2 * n2) throw new Error(`pads should be ${2 * n2}D`);
            if (0 !== e2.kernelShape.length && e2.kernelShape.length !== t2[1].dims.length - 2) throw new Error("invalid kernel shape");
            if ("float32" !== t2[0].type || "float32" !== t2[1].type) throw new Error("Conv input(X,W) should be float tensor");
            if (3 === t2.length && "float32" !== t2[2].type) throw new Error("Conv input(bias) should be float tensor");
          };
        }, 5193: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.parseDepthToSpaceAttributes = e.depthToSpace = void 0;
          const r = n(3738);
          e.depthToSpace = (t2, e2, n2) => {
            i2(e2);
            const o = n2.blocksize, a = o * o, s = "DCR" === n2.mode ? [0, 3, 4, 1, 5, 2] : [0, 1, 4, 2, 5, 3], u = "DCR" === n2.mode ? [e2[0].dims[0], o, o, e2[0].dims[1] / a, e2[0].dims[2], e2[0].dims[3]] : [e2[0].dims[0], e2[0].dims[1] / a, o, o, e2[0].dims[2], e2[0].dims[3]], c = t2.reshapeUnpacked(e2[0], u), l = { perm: s, cacheKey: `${s}` }, [p] = (0, r.transpose)(t2, [c], l), f = [e2[0].dims[0], e2[0].dims[1] / a, e2[0].dims[2] * o, e2[0].dims[3] * o];
            return [t2.reshapeUnpacked(p, f)];
          }, e.parseDepthToSpaceAttributes = (t2) => {
            const e2 = t2.attributes.getInt("blocksize");
            if (e2 < 1) throw new Error(`blocksize must be >= 1, but got : ${e2} for DepthToSpace`);
            const n2 = t2.attributes.getString("mode", "DCR");
            if ("DCR" !== n2 && "CRD" !== n2) throw new Error(`unrecognized mode: ${n2} for DepthToSpace`);
            return { mode: n2, blocksize: e2 };
          };
          const i2 = (t2) => {
            if (1 !== t2.length) throw new Error(`DepthToSpace expect 1 inputs, but got ${t2.length}`);
            if ("string" === t2[0].type || 4 !== t2[0].dims.length) throw new TypeError("DepthToSpace input should be a 4-D numeric tensor");
          };
        }, 9828: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.createDotProductProgramInfoLoader = void 0;
          const r = n(2517), i2 = n(5060), o = n(2039), a = n(2823), s = n(3248);
          e.createDotProductProgramInfoLoader = (t2, e2, n2, u) => {
            const c = ((t3, e3) => ({ name: "ConvDotProduct", inputNames: t3 ? ["Im2Col", "K", "B"] : ["Im2Col", "K"], inputTypes: t3 ? [o.TextureType.unpacked, o.TextureType.packedLastDimension, o.TextureType.unpacked] : [o.TextureType.unpacked, o.TextureType.packedLastDimension], cacheKey: e3.activationCacheKey }))(e2.length > 2, u);
            return Object.assign(Object.assign({}, c), { get: () => ((t3, e3, n3, u2, c2) => {
              const l = n3[0].dims, p = n3[1].dims, f = [p[0], Math.ceil(l[1] * p[2] * p[3] / 4)], d = (0, s.calculateIm2ColDims)(l, p, u2), [h, g] = t3.calculateTextureWidthAndHeight(f, o.TextureType.packedLastDimension), b = r.ShapeUtil.computeStrides(d), [m, y] = t3.calculateTextureWidthAndHeight(d, o.TextureType.packedLastDimension), _ = u2.length, v = n3.length < 3 ? "0.0" : "_B(b)", w = Math.ceil(l[1] * p[2] * p[3] / 4), { activationFunction: x, applyActivation: T } = (0, a.getActivationSnippet)(c2), S = (0, i2.getGlsl)(t3.session.backend.glContext.version), O = `
${x}
float process(int indices[${_}]) {
  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] * ${b[0]} + im2col[1] * ${b[1]} + im2col[2] * ${b[2]};
  int kernelOffset = indices[1] * ${f[1]};
  float value = ${v};
  for (int i = 0; i < ${w}; ++i) {
    vec2 im2colCoords = offsetToCoords(im2colOffset, ${m}, ${y});
    vec2 kernelCoords = offsetToCoords(kernelOffset, ${h}, ${g});
    value += dot(${S.texture2D}(Im2Col, im2colCoords), ${S.texture2D}(K, kernelCoords));
    ++im2colOffset;
    ++kernelOffset;
  }
  ${T}
  return value;
}`;
              return Object.assign(Object.assign({}, e3), { output: { dims: u2, type: n3[0].type, textureType: o.TextureType.unpacked }, shaderSource: O });
            })(t2, c, e2, n2, u) });
          };
        }, 7992: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.parseFlattenAttributes = e.flatten = void 0;
          const r = n(2517);
          e.flatten = (t2, e2, n2) => {
            i2(e2, n2);
            const o = r.ShapeUtil.flattenShape(e2[0].dims, n2);
            return [t2.reshapeUnpacked(e2[0], o)];
          }, e.parseFlattenAttributes = (t2) => t2.attributes.getInt("axis", 1);
          const i2 = (t2, e2) => {
            if (!t2 || 1 !== t2.length) throw new Error("Flatten requires 1 input.");
            const n2 = t2[0].dims.length;
            if (0 === n2) throw new Error("scalar tensor is not supported.");
            if (e2 < -n2 || e2 > n2) throw new Error("Invalid axis");
            if ("string" === t2[0].type) throw new Error("string tensor is not supported.");
          };
        }, 2823: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.parseInternalActivationAttributes = e.getActivationSnippet = void 0;
          const r = n(2517), i2 = n(4909);
          e.getActivationSnippet = function(t2) {
            let e2;
            switch (t2.activation) {
              case "Relu":
                e2 = (0, i2.glslRelu)();
                break;
              case "Sigmoid":
                e2 = (0, i2.glslSigmoid)();
                break;
              case "Clip":
                e2 = (0, i2.glslClip)(t2.clipMin, t2.clipMax);
                break;
              default:
                return { activationFunction: "", applyActivation: "" };
            }
            const n2 = e2.name;
            return { activationFunction: e2.body, applyActivation: `value = ${n2}_(value);` };
          }, e.parseInternalActivationAttributes = (t2) => {
            const e2 = t2.getString("activation", "");
            if ("Clip" === e2) {
              const [n2, i3] = t2.getFloats("activation_params", [r.MIN_CLIP, r.MAX_CLIP]);
              return { activation: e2, clipMax: i3, clipMin: n2, activationCacheKey: `${e2}:${n2},${i3}` };
            }
            return { activation: e2, activationCacheKey: e2 };
          };
        }, 1253: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.parseGatherAttributes = e.gather = void 0;
          const r = n(246), i2 = n(782), o = n(2517), a = n(2039);
          e.gather = (t2, e2, n2) => (c(e2, n2.axis), [t2.run(u(t2, e2, n2), e2)]), e.parseGatherAttributes = (t2) => (0, r.createAttributeWithCacheKey)({ axis: t2.attributes.getInt("axis", 0) });
          const s = { name: "Gather", inputNames: ["A", "B"], inputTypes: [a.TextureType.unpacked, a.TextureType.unpacked] }, u = (t2, e2, n2) => {
            const r2 = Object.assign(Object.assign({}, s), { cacheHint: n2.cacheKey });
            return Object.assign(Object.assign({}, r2), { get: () => ((t3, e3, n3, r3) => {
              const i3 = n3[0].dims.slice(), s2 = n3[1].dims.slice(), u2 = new Array(i3.length + s2.length - 1);
              r3 = o.ShapeUtil.normalizeAxis(r3, i3.length);
              const c2 = [];
              for (let t4 = 0; t4 < u2.length; t4++) t4 < r3 ? (u2[t4] = i3[t4], c2.push(`inputIdx[${t4}] = outputIdx[${t4}];`)) : t4 < r3 + s2.length ? (u2[t4] = s2[t4 - r3], c2.push(`indexDataIdx[${t4 - r3}] = outputIdx[${t4}];`)) : (u2[t4] = i3[t4 - s2.length + 1], c2.push(`inputIdx[${t4 - s2.length + 1}] = outputIdx[${t4}];`));
              const l = `
      float process(int outputIdx[${u2.length || 1}]) {
        int inputIdx[${i3.length}];
        int indexDataIdx[${s2.length || 1}];
        indexDataIdx[0] = 0;
        ${c2.join("\n        ")}
        int idx = int(_B(indexDataIdx));
        inputIdx[${r3}] = idx < 0 ? idx + ${i3[r3]} : idx;
        return _A(inputIdx);
      }`;
              return Object.assign(Object.assign({}, e3), { output: { dims: u2, type: n3[0].type, textureType: a.TextureType.unpacked }, shaderSource: l });
            })(0, r2, e2, n2.axis) });
          }, c = (t2, e2) => {
            if (!t2 || 2 !== t2.length) throw new Error("Gather requires 2 inputs.");
            const n2 = t2[0].dims.length;
            if (n2 < 1) throw new Error("Invalid input shape.");
            if (e2 < -n2 || e2 > n2 - 1) throw new Error("Invalid axis.");
            if (-1 === i2.NUMBER_TYPES.indexOf(t2[0].type)) throw new Error("Invaid input type.");
            if ("int32" !== t2[1].type && "int16" !== t2[1].type) throw new Error("Invaid input type.");
          };
        }, 4776: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.parseGemmAttributesV11 = e.parseGemmAttributesV7 = e.gemm = void 0;
          const r = n(246), i2 = n(2517), o = n(2039);
          e.gemm = (t2, e2, n2) => (c(e2, n2), [t2.run(s(e2, n2), e2)]);
          const a = (t2, e2) => {
            const n2 = 0 !== t2.attributes.getInt("transA", 0), i3 = 0 !== t2.attributes.getInt("transB", 0), o2 = t2.attributes.getFloat("alpha", 1), a2 = t2.attributes.getFloat("beta", 1);
            return (0, r.createAttributeWithCacheKey)({ transA: n2, transB: i3, alpha: o2, beta: a2, isOptionalC: e2 });
          };
          e.parseGemmAttributesV7 = (t2) => a(t2, false), e.parseGemmAttributesV11 = (t2) => a(t2, true);
          const s = (t2, e2) => {
            const n2 = { name: "Gemm", inputNames: 3 === t2.length ? ["A", "B", "C"] : ["A", "B"], inputTypes: 3 === t2.length ? [o.TextureType.unpacked, o.TextureType.unpacked, o.TextureType.unpacked] : [o.TextureType.unpacked, o.TextureType.unpacked], key: e2.cacheKey };
            return Object.assign(Object.assign({}, n2), { get: () => u(n2, t2, e2) });
          }, u = (t2, e2, n2) => {
            const r2 = e2[0].dims.slice(), a2 = e2[1].dims.slice(), [s2, u2] = i2.GemmUtil.getShapeOfGemmResult(r2, n2.transA, a2, n2.transB, 3 === e2.length ? e2[2].dims : void 0), c2 = [s2, u2];
            if (!c2) throw new Error("Can't use gemm on the given tensors");
            let l = r2[r2.length - 1], p = "";
            n2.transA && (l = r2[0]), n2.transA && n2.transB ? p = "value += _A_T(a) * _B_T(b);" : n2.transA && !n2.transB ? p = "value += _A_T(a) * _B(b);" : !n2.transA && n2.transB ? p = "value += _A(a) * _B_T(b);" : n2.transA || n2.transB || (p = "value += _A(a) * _B(b);");
            const f = c2.length, d = `
      float process(int indices[${f}]) {
          int a[${f}];
          int b[${f}];
          ${3 === e2.length ? `int c[${e2[2].dims.length}];` : ""}

          copyVec(indices, a);
          copyVec(indices, b);
          ${3 === e2.length ? "bcastIndices_C(indices, c);" : ""}

          float value = 0.0;
          for (int k=0; k<${l}; ++k) {
              a[${f - 1}] = k;
              b[${f - 2}] = k;
              ${p}
          }

          value = value * alpha;
          ${3 === e2.length ? "value += beta * _C(c);" : ""}
          return value;
      }`;
            return Object.assign(Object.assign({}, t2), { output: { dims: c2, type: e2[0].type, textureType: o.TextureType.unpacked }, variables: [{ name: "alpha", type: "float", data: n2.alpha }, { name: "beta", type: "float", data: n2.beta }], shaderSource: d });
          }, c = (t2, e2) => {
            if (!t2) throw new Error("Input is missing");
            if (e2.isOptionalC && (t2.length < 2 || t2.length > 3)) throw new Error("Invaid input shape.");
            if (!e2.isOptionalC && 3 !== t2.length) throw new Error("Gemm requires 3 inputs");
            if (3 === t2.length && 1 !== t2[2].dims.length && 2 !== t2[2].dims.length) throw new Error("Invalid input shape of C");
            if ("float32" !== t2[0].type && "float64" !== t2[0].type || "float32" !== t2[1].type && "float64" !== t2[1].type || 3 === t2.length && "float32" !== t2[2].type && "float64" !== t2[2].type) throw new Error("Invalid input type.");
            if (t2[0].type !== t2[1].type || 3 === t2.length && t2[0].type !== t2[2].type) throw new Error("Input types are mismatched");
          };
        }, 8555: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.createPackedIm2ColProgramInfoLoader = void 0;
          const r = n(5060), i2 = n(2039), o = n(2827);
          e.createPackedIm2ColProgramInfoLoader = (t2, e2, n2, a, s) => {
            const u = (c = s.cacheKey, { name: "Im2Col (packed)", inputNames: ["A"], inputTypes: [i2.TextureType.packed], cacheHint: c });
            var c;
            return Object.assign(Object.assign({}, u), { get: () => ((t3, e3, n3, a2, s2, u2) => {
              const c2 = n3.dims, l = a2.dims, p = s2.length, f = [l[1] * l[2] * l[3], s2[2] * s2[3]], d = l[2] * l[3], h = (0, o.unpackFromChannel)(), g = (0, r.getGlsl)(t3.session.backend.glContext.version);
              let b = "";
              for (let t4 = 0; t4 <= 1; t4++) for (let e4 = 0; e4 <= 1; e4++) b += `
            blockIndex = rc.x + ${e4};
            pos = rc.y + ${t4};

            if(blockIndex < ${f[1]} && pos < ${f[0]}) {
              offsetY = int(blockIndex / (${s2[p - 1]})) * ${u2.strides[0]} -
                ${u2.pads[0]};
              d0 = offsetY + ${u2.dilations[0]} * (imod(pos, ${d}) / ${l[2]});

              if(d0 < ${c2[2]} && d0 >= 0) {
                offsetX = imod(blockIndex, ${s2[p - 1]}) * ${u2.strides[1]} -
                  ${u2.pads[1]};
                d1 = offsetX + ${u2.dilations[1]} * imod(imod(pos, ${d}), ${l[2]});

                if(d1 < ${c2[3]} && d1 >= 0) {

                  ch = int(float(pos)/ ${d}.);
                    innerDims = vec2(d0, d1);
                    result[${2 * t4 + e4}] = getChannel(
                      getA(0, ch, int(innerDims.x),
                      int(innerDims.y)), innerDims);
                }
              }
            }

          `;
              const m = `
      ${h}

      void main() {
        ivec2 rc = getOutputCoords();
          vec4 result = vec4(0.0);
          int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
          vec2 innerDims;
          ${b}
          ${g.output} = result;
      }
            `;
              return Object.assign(Object.assign({}, e3), { output: { dims: f, type: n3.type, textureType: i2.TextureType.packed }, shaderSource: m, hasMain: true });
            })(t2, u, e2, n2, a, s) });
          };
        }, 3248: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.calculateIm2ColDims = e.createIm2ColProgramInfoLoader = void 0;
          const r = n(2039);
          e.createIm2ColProgramInfoLoader = (t2, n2, i2, o, a) => {
            const s = (u = a.cacheKey, { name: "Im2Col", inputNames: ["X"], inputTypes: [r.TextureType.unpacked], cacheHint: u });
            var u;
            return Object.assign(Object.assign({}, s), { get: () => ((t3, n3, i3, o2, a2, s2) => {
              const u2 = i3.dims, c = o2.dims, l = a2.length, p = (0, e.calculateIm2ColDims)(u2, c, a2, 4), f = `
        const int XC = ${u2[1]};
        const int XH = ${u2[2]};
        const int XW = ${u2[3]};
        const int KH = ${s2.kernelShape[0]};
        const int KW = ${s2.kernelShape[1]};
        const int dilationH = ${s2.dilations[0]};
        const int dilationW = ${s2.dilations[1]};
        const int strideH = ${s2.strides[0]};
        const int strideW = ${s2.strides[1]};
        const int padH = ${s2.pads[0]};
        const int padW = ${s2.pads[1]};
        const int KHKW = KH*KW;
        const int XCKHKW = XC * KHKW;
        const int outputChannels = 4;
        vec4 process(int indices[${l}]) {
          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[${u2.length}];
              x[0] = b;
              x[1] = patchC;
              x[2] = xh2;
              x[3] = xw2;
              if(xh2 >= 0 &&
                  xh2 < XH &&
                  xw2 >= 0 &&
                  xw2 < XW) {
                value[i] = _X(x);
              }
            }
            ++p;
          }
          return value;
        }
        `;
              return Object.assign(Object.assign({}, n3), { output: { dims: p, type: i3.type, textureType: r.TextureType.packedLastDimension }, shaderSource: f });
            })(0, s, n2, i2, o, a) });
          }, e.calculateIm2ColDims = (t2, e2, n2, r2 = 4) => [n2[0], n2[2], n2[3], Math.ceil(t2[1] * e2[2] * e2[3] / r2)];
        }, 6572: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.parseImageScalerAttributes = e.imageScaler = void 0;
          const r = n(246), i2 = n(2039);
          e.imageScaler = (t2, e2, n2) => (u(e2), [t2.run(a(t2, e2, n2), e2)]), e.parseImageScalerAttributes = (t2) => {
            const e2 = t2.attributes.getFloat("scale"), n2 = t2.attributes.getFloats("bias");
            return (0, r.createAttributeWithCacheKey)({ scale: e2, bias: n2 });
          };
          const o = { name: "ImageScaler", inputNames: ["X"], inputTypes: [i2.TextureType.unpacked] }, a = (t2, e2, n2) => {
            const r2 = Object.assign(Object.assign({}, o), { cacheHint: n2.cacheKey });
            return Object.assign(Object.assign({}, r2), { get: () => ((t3, e3, n3, r3) => {
              const o2 = n3[0].dims.slice(), a2 = o2.length, u2 = `
      ${s(r3.bias.length)}
      float process(int indices[${a2}]) {
        return _X(indices) * scale + getBias(bias, indices[1]);
      }`;
              return Object.assign(Object.assign({}, e3), { output: { dims: o2, type: n3[0].type, textureType: i2.TextureType.unpacked }, variables: [{ name: "bias", type: "float", arrayLength: r3.bias.length, data: r3.bias }, { name: "scale", type: "float", data: r3.scale }], shaderSource: u2 });
            })(0, r2, e2, n2) });
          }, s = (t2) => {
            const e2 = [`float getBias(float bias[${t2}], int channel) {`];
            for (let n2 = 0; n2 < t2; ++n2) 0 === n2 ? e2.push(`	if (channel == ${n2}) { return bias[${n2}]; }`) : n2 === t2 - 1 ? e2.push(`	else { return bias[${n2}]; }`) : e2.push(`	else if (channel == ${n2}) { return bias[${n2}]; }`);
            return e2.push("	}"), e2.join("\n");
          }, u = (t2) => {
            if (!t2 || 1 !== t2.length) throw new Error("ImageScaler requires 1 input.");
            if (4 !== t2[0].dims.length) throw new Error("Invalid input shape.");
            if ("float32" !== t2[0].type && "float64" !== t2[0].type) throw new Error("Invalid input type.");
          };
        }, 3346: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.parseInstanceNormalizationAttributes = e.instanceNormalization = void 0;
          const r = n(5060), i2 = n(2039);
          e.instanceNormalization = (t2, e2, n2) => {
            c(e2);
            const r2 = t2.run(a(e2[0]), e2);
            return [t2.run(u(t2, e2[0], n2, r2.dims), [e2[0], r2, e2[1], e2[2]])];
          }, e.parseInstanceNormalizationAttributes = (t2) => t2.attributes.getFloat("epsilon", 1e-5);
          const o = { name: "InstanceNormalization_MeanAndVariance", inputNames: ["X"], inputTypes: [i2.TextureType.unpacked] }, a = (t2) => Object.assign(Object.assign({}, o), { get: () => ((t3, e2) => {
            const n2 = e2.dims.slice(), r2 = n2[1], o2 = n2[2] * n2[3], a2 = [n2[0], r2], s2 = `
      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<${n2[2]}; a2++) {
          a[2] = a2;
          for(int a3=0; a3<${n2[3]}; a3++) {
            a[3] = a3;
            float x = _X(a);
            temp += x;
          }
        }
        float mean = temp / float(${o2});
        temp = 0.0;
        for(int a2=0; a2<${n2[2]}; a2++) {
          a[2] = a2;
          for(int a3=0; a3<${n2[3]}; a3++) {
            a[3] = a3;
            float x = _X(a);
            temp += (x - mean) * (x - mean);
          }
        }
        v.r = mean;
        v.g = temp / float(${o2});

        return v;
      }`;
            return Object.assign(Object.assign({}, t3), { output: { dims: a2, type: e2.type, textureType: i2.TextureType.packedLastDimension }, shaderSource: s2 });
          })(o, t2) }), s = { name: "InstanceNormalization_ComputeOutput", inputNames: ["X", "MeanAndVariance", "Scale", "B"], inputTypes: [i2.TextureType.unpacked, i2.TextureType.packedLastDimension, i2.TextureType.unpacked, i2.TextureType.unpacked] }, u = (t2, e2, n2, o2) => {
            const a2 = Object.assign(Object.assign({}, s), { cacheHint: `${n2}` });
            return Object.assign(Object.assign({}, a2), { get: () => ((t3, e3, n3, o3, a3) => {
              const s2 = (0, r.getGlsl)(t3.session.backend.glContext.version), [u2, c2] = t3.calculateTextureWidthAndHeight(a3, i2.TextureType.packedLastDimension), [l, p] = [u2 / 4, c2], f = `
      vec4 get_MeanAndVariance(int[2] mv) {
        int offset = indicesToOffset_MeanAndVariance(mv);
        vec2 coords = offsetToCoords(offset, ${l}, ${p});
        return ${s2.texture2D}(MeanAndVariance, coords);
      }

      float process(int[4] indices) {
        int mv[2];
        mv[0] = indices[0];
        mv[1] = indices[1];
        vec4 mean_and_variance = get_MeanAndVariance(mv);
        float mean = mean_and_variance.r;
        float variance = mean_and_variance.g;

        int sb[1];
        sb[0] = indices[1];
        float scale = _Scale(sb);
        float b = _B(sb);

        return scale * (_X(indices) - mean) / sqrt(variance + epsilon) + b;
      }`;
              return Object.assign(Object.assign({}, e3), { output: { dims: n3.dims, type: n3.type, textureType: i2.TextureType.unpacked }, variables: [{ name: "epsilon", type: "float", data: o3 }], shaderSource: f });
            })(t2, a2, e2, n2, o2) });
          }, c = (t2) => {
            if (!t2 || 3 !== t2.length) throw new Error("InstanceNormalization requires 3 inputs.");
            const e2 = t2[0], n2 = t2[1], r2 = t2[2];
            if (e2.dims.length < 3 || 1 !== n2.dims.length || 1 !== r2.dims.length) throw new Error("Invalid input shape.");
            if (n2.dims[0] !== e2.dims[1] || r2.dims[0] !== e2.dims[1]) throw new Error("Input shapes are mismatched.");
            if ("float32" !== e2.type && "float64" !== e2.type || "float32" !== n2.type && "float64" !== n2.type || "float32" !== r2.type && "float64" !== r2.type) throw new Error("Invalid input type.");
            if (4 !== t2[0].dims.length) throw new Error("Only support 4-D input shape.");
          };
        }, 708: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.createPackedMatmulProgramInfoLoader = void 0;
          const r = n(2517), i2 = n(5060), o = n(2039), a = n(9390), s = n(2823), u = n(5623);
          e.createPackedMatmulProgramInfoLoader = (t2, e2, n2) => {
            const c = (l = e2.length > 2, p = n2.activationCacheKey, { name: "MatMul (packed)", inputNames: l ? ["A", "B", "Bias"] : ["A", "B"], inputTypes: l ? [o.TextureType.packed, o.TextureType.packed, o.TextureType.packed] : [o.TextureType.packed, o.TextureType.packed], cacheHint: p });
            var l, p;
            return Object.assign(Object.assign({}, c), { get: () => ((t3, e3, n3, c2) => {
              const l2 = n3.length > 2, p2 = l2 ? "value += getBiasForMatmul();" : "", f = n3[0].dims, d = n3[1].dims, h = r.BroadcastUtil.calcShape(f, d, true), g = !r.ShapeUtil.areEqual(n3[0].dims, n3[1].dims);
              if (!h) throw new Error("Can't use matmul on the given tensors");
              const b = f[f.length - 1], m = Math.ceil(b / 2), y = f.length, _ = d.length, v = (0, i2.getGlsl)(t3.session.backend.glContext.version), w = (0, a.getCoordsDataType)(h.length), x = h.length, T = (0, a.getGlChannels)(), { activationFunction: S, applyActivation: O } = (0, s.getActivationSnippet)(c2), A = l2 ? `${(0, u.getBiasForMatmul)(w, T, n3[2].dims, h, true)}` : "", E = g ? `${(function(t4, e4, n4, i3) {
                let o2 = [], a2 = [];
                const s2 = n4[0].dims, u2 = n4[1].dims, c3 = s2.length, l3 = u2.length, p3 = i3.length, f2 = p3 - c3, d2 = p3 - l3;
                o2 = s2.map(((t5, n5) => `coords.${e4[n5 + f2]}`)), o2[c3 - 1] = "i*2", o2.join(", "), a2 = u2.map(((t5, n5) => `coords.${e4[n5 + d2]}`)), a2[l3 - 2] = "i*2", a2.join(", ");
                const h2 = r.BroadcastUtil.getBroadcastDims(s2, i3), g2 = r.BroadcastUtil.getBroadcastDims(u2, i3), b2 = h2.map(((t5) => `coords.${e4[t5 + f2]} = 0;`)).join("\n"), m2 = g2.map(((t5) => `coords.${e4[t5 + d2]} = 0;`)).join("\n"), y2 = `int lastDim = coords.${e4[p3 - 1]};
  coords.${e4[p3 - 1]} = coords.${e4[p3 - 2]};
  coords.${e4[p3 - 2]} = lastDim;`;
                return `
vec4 getAAtOutCoordsMatmul(int i) {
  ${t4} coords = getOutputCoords();
  ${y2}
  ${b2}
  vec4 outputValue = getA(${o2});
  return outputValue;
}

vec4 getBAtOutCoordsMatmul(int i) {
  ${t4} coords = getOutputCoords();
  ${y2}
  ${m2}
  vec4 outputValue = getB(${a2});
  return outputValue;
}`;
              })(w, T, n3, h)}` : "", I = g ? "getAAtOutCoordsMatmul(i)" : `getA(${(function(t4, e4) {
                let n4 = "";
                for (let r2 = 0; r2 < e4 - 2; r2++) n4 += `rc.${t4[r2]}, `;
                return n4 += `rc.${t4[e4 - 2]}, i*2`, n4;
              })(T, y)})`, P = g ? "getBAtOutCoordsMatmul(i)" : `getB(${(function(t4, e4) {
                let n4 = "";
                for (let r2 = 0; r2 < e4 - 2; r2++) n4 += `rc.${t4[r2]}, `;
                return n4 += `i*2, rc.${t4[e4 - 1]}`, n4;
              })(T, _)})`, D = `
            ${E}
            ${A}
            ${S}
            void main() {
              ${g ? "" : `${w} rc =
          getOutputCoords(); int lastDim = rc.${T[x - 1]}; rc.${T[x - 1]} =
          rc.${T[x - 2]}; rc.${T[x - 2]} = lastDim;
      `}

              vec4 value = vec4(0);
              for (int i = 0; i < ${m}; i++) {
                vec4 a = ${I};
                vec4 b = ${P};

                value += (a.rrbb * b.rgrg);
                value += (a.ggaa * b.baba);
              }
              ${p2}
              ${O}
              ${v.output} = value;
            }`;
              return Object.assign(Object.assign({}, e3), { output: { dims: h, type: n3[0].type, textureType: o.TextureType.packed }, shaderSource: D, hasMain: true });
            })(t2, c, e2, n2) });
          };
        }, 5623: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.getBiasForMatmul = e.createMatmulProgramInfoLoader = e.parseMatMulAttributes = e.matMul = void 0;
          const r = n(2517), i2 = n(2039), o = n(9390), a = n(2823), s = n(708);
          function u(t2, e2) {
            const n2 = (s2 = t2.length > 2, u2 = e2.activationCacheKey, { name: "MatMul", inputNames: s2 ? ["A", "B", "Bias"] : ["A", "B"], inputTypes: s2 ? [i2.TextureType.unpacked, i2.TextureType.unpacked, i2.TextureType.unpacked] : [i2.TextureType.unpacked, i2.TextureType.unpacked], cacheHint: u2 });
            var s2, u2;
            return Object.assign(Object.assign({}, n2), { get: () => (function(t3, e3, n3) {
              const s3 = e3[0].dims, u3 = e3[1].dims, c2 = r.BroadcastUtil.calcShape(s3, u3, true);
              if (!c2) throw new Error("Can't use matmul on the given tensors");
              const p = (0, o.getCoordsDataType)(c2.length), f = (0, o.getGlChannels)(), { activationFunction: d, applyActivation: h } = (0, a.getActivationSnippet)(n3), g = e3.length > 2, b = g ? "value += getBiasForMatmul();" : "", m = g ? `${l(p, f, e3[2].dims, c2, false)}` : "", y = c2.length, _ = s3.length, v = u3.length, w = `
    ${d}
    ${m}
    float process(int indices[${y}]) {
        int a[${_}];
        int b[${v}];
        bcastMatmulIndices_A(indices, a);
        bcastMatmulIndices_B(indices, b);

        float value;
        for (int k=0; k<${s3[s3.length - 1]}; ++k) {
            a[${_ - 1}] = k;
            b[${v - 2}] = k;
            value += _A(a) * _B(b);
        }
        ${b}
        ${h}
        return value;
    }`;
              return Object.assign(Object.assign({}, t3), { output: { dims: c2, type: e3[0].type, textureType: i2.TextureType.unpacked }, shaderSource: w });
            })(n2, t2, e2) });
          }
          e.matMul = (t2, e2, n2) => (c(e2), t2.session.pack ? [t2.run((0, s.createPackedMatmulProgramInfoLoader)(t2, e2, n2), e2)] : [t2.run(u(e2, n2), e2)]), e.parseMatMulAttributes = (t2) => (0, a.parseInternalActivationAttributes)(t2.attributes), e.createMatmulProgramInfoLoader = u;
          const c = (t2) => {
            if (!t2 || 2 !== t2.length) throw new Error("MatMul requires 2 inputs.");
            if (t2[0].dims[t2[0].dims.length - 1] !== t2[1].dims[t2[1].dims.length - 2]) throw new Error("shared dimension does not match.");
            if ("float32" !== t2[0].type && "float64" !== t2[0].type || "float32" !== t2[1].type && "float64" !== t2[1].type) throw new Error("inputs should be float type");
            if (t2[0].type !== t2[1].type) throw new Error("inputs types should match");
          };
          function l(t2, e2, n2, i3, o2) {
            let a2 = "";
            const s2 = n2.length, u2 = i3.length, c2 = u2 - s2;
            a2 = u2 < 2 && s2 > 0 ? "coords" : n2.map(((t3, n3) => `coords.${e2[n3 + c2]}`)).join(", ");
            const l2 = r.BroadcastUtil.getBroadcastDims(n2, i3).map(((t3) => `coords.${e2[t3 + c2]} = 0;`)).join("\n");
            let p = "vec4(outputValue.xx, outputValue.yy)";
            return 1 === r.ShapeUtil.size(n2) && (p = "vec4(outputValue.x)"), o2 ? `
vec4 getBiasForMatmul() {
  ${t2} coords = getOutputCoords();
  ${l2}
  vec4 outputValue = getBias(${a2});
  return ${p};
}` : `
float getBiasForMatmul() {
  ${t2} coords = getOutputCoords();
  ${l2}
  return getBias(coords.x);
}`;
          }
          e.getBiasForMatmul = l;
        }, 2403: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.createPackProgramInfoLoader = void 0;
          const r = n(5060), i2 = n(2039), o = n(9390), a = n(2827), s = { name: "pack", inputNames: ["A"], inputTypes: [i2.TextureType.unpackedReversed] };
          e.createPackProgramInfoLoader = (t2, e2) => Object.assign(Object.assign({}, s), { get: () => ((t3, e3) => {
            const n2 = (0, r.getGlsl)(t3.session.backend.glContext.version), u = e3.dims, c = u.length, l = e3.dims.length, p = (0, o.getCoordsDataType)(l), f = (0, a.getChannels)("rc", l), d = (h = l, g = f, b = u[u.length - 2], m = u[u.length - 1], 0 === h || 1 === h ? "" : `
    int r = ${g[h - 2]};
    int c = ${g[h - 1]};
    int rp1 = ${g[h - 2]} + 1;
    int cp1 = ${g[h - 1]} + 1;
    bool rEdge = rp1 >= ${m};
    bool cEdge = cp1 >= ${b};
    `);
            var h, g, b, m;
            let y;
            y = 0 === c ? [1, 1] : 1 === c ? [u[0], 1] : [u[l - 1], u[l - 2]];
            const _ = (function(t4, e4, n3) {
              if (0 === t4) return "false";
              if (1 === t4) return `rc > ${e4[0]}`;
              let r2 = "";
              for (let i3 = t4 - 2; i3 < t4; i3++) r2 += `${n3[i3]} >= ${e4[i3 - t4 + 2]}`, i3 < t4 - 1 && (r2 += "||");
              return r2;
            })(l, y, f), v = (function(t4, e4) {
              const n3 = t4.length;
              if (0 === n3) return "getA(), 0, 0, 0";
              if (1 === n3) return `getA(rc),
            rc + 1 >= ${t4[0]} ? 0. : getA(rc + 1),
            0, 0`;
              let r2 = "";
              if (n3 > 2) for (let t5 = 0; t5 < n3 - 2; ++t5) r2 += `${e4[t5]},`;
              return `getA(${r2}r, c),
          rEdge ? 0. : getA(${r2}rp1, c),
          cEdge ? 0. : getA(${r2}r, cp1),
          rEdge || cEdge ? 0. : getA(${r2}rp1, cp1)`;
            })(u, f), w = `
        void main() {
          ${p} rc = getOutputCoords();

          if(${_}) {
            ${n2.output} = vec4(0);
          } else {
            ${d}

            ${n2.output} = vec4(${v});
          }
        }
      `;
            return Object.assign(Object.assign({}, s), { hasMain: true, output: { dims: e3.dims, type: e3.type, textureType: i2.TextureType.packed }, shaderSource: w });
          })(t2, e2) });
        }, 2827: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.unpackFromChannel = e.getChannels = e.getVecChannels = void 0;
          const r = n(9390);
          function i2(t2, e2) {
            return (0, r.getGlChannels)(e2).map(((e3) => `${t2}.${e3}`));
          }
          e.getVecChannels = i2, e.getChannels = function(t2, e2) {
            return 1 === e2 ? [t2] : i2(t2, e2);
          }, e.unpackFromChannel = function() {
            return "\n    float getChannel(vec4 frag, int dim) {\n      int modCoord = imod(dim, 2);\n      return modCoord == 0 ? frag.r : frag.g;\n    }\n\n    float getChannel(vec4 frag, vec2 innerDims) {\n      vec2 modCoord = mod(innerDims, 2.);\n      return modCoord.x == 0. ?\n        (modCoord.y == 0. ? frag.r : frag.g) :\n        (modCoord.y == 0. ? frag.b : frag.a);\n    }\n  ";
          };
        }, 2870: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.parsePadAttributesV11 = e.padV11 = e.parsePadAttributesV2 = e.padV2 = void 0;
          const r = n(246), i2 = n(2517), o = n(5060), a = n(2039), s = { name: "Pad", inputNames: ["A"], inputTypes: [a.TextureType.unpacked] };
          e.padV2 = (t2, e2, n2) => (l(e2), [t2.run(Object.assign(Object.assign({}, s), { cacheHint: n2.cacheKey, get: () => c(t2, e2[0], n2) }), e2)]), e.parsePadAttributesV2 = (t2) => {
            const e2 = t2.attributes.getString("mode", "constant"), n2 = t2.attributes.getFloat("value", 0), i3 = t2.attributes.getInts("pads");
            return (0, r.createAttributeWithCacheKey)({ mode: e2, value: n2, pads: i3 });
          }, e.padV11 = (t2, n2, r2) => {
            p(n2);
            const i3 = u(t2, n2, r2);
            return (0, e.padV2)(t2, [n2[0]], i3);
          }, e.parsePadAttributesV11 = (t2) => t2.attributes.getString("mode", "constant");
          const u = (t2, e2, n2) => {
            if (!t2.session.isInitializer(e2[1].dataId) || e2.length >= 3 && !t2.session.isInitializer(e2[2].dataId)) throw new Error("dynamic pad attributes are not allowed");
            const i3 = Array.from(e2[1].integerData), o2 = e2.length >= 3 ? e2[2].floatData[0] : 0;
            return (0, r.createAttributeWithCacheKey)({ mode: n2, pads: i3, value: o2 });
          }, c = (t2, e2, n2) => {
            const r2 = i2.ShapeUtil.padShape(e2.dims.slice(), n2.pads), o2 = r2.length, s2 = `
      ${f(t2, e2, n2)}
      float process(int[${o2}] indices) {
          return padA(indices);
      }`;
            return { name: "Pad", inputNames: ["A"], inputTypes: [a.TextureType.unpacked], output: { dims: r2, type: e2.type, textureType: a.TextureType.unpacked }, shaderSource: s2 };
          }, l = (t2) => {
            if (!t2 || 1 !== t2.length) throw new Error("Pad requires 1 input");
            if ("float32" !== t2[0].type && "float64" !== t2[0].type) throw new Error("Invalid input type.");
          }, p = (t2) => {
            if (!t2 || 2 !== t2.length && 3 !== t2.length) throw new Error("Pad requires 2 or 3 inputs");
            if ("int32" !== t2[1].type) throw new Error("Invalid input type.");
            if (t2.length >= 3 && "string" === t2[2].type) throw new Error("Invalid input type.");
          }, f = (t2, e2, n2) => {
            const r2 = (0, o.getGlsl)(t2.session.backend.glContext.version), [s2, u2] = t2.calculateTextureWidthAndHeight(e2.dims, a.TextureType.unpacked), c2 = i2.ShapeUtil.computeStrides(e2.dims);
            switch (n2.mode) {
              case "constant":
                return d(r2, e2.dims, c2, s2, u2, n2.pads, n2.value);
              case "reflect":
                return h(r2, e2.dims, c2, s2, u2, n2.pads);
              case "edge":
                return g(r2, e2.dims, c2, s2, u2, n2.pads);
              default:
                throw new Error("Invalid mode");
            }
          }, d = (t2, e2, n2, r2, i3, o2, a2) => {
            const s2 = e2.length;
            let u2 = "";
            for (let t3 = s2 - 1; t3 >= 0; --t3) u2 += `
        k = m[${t3}] - ${o2[t3]};
        if (k < 0)  return constant;
        if (k >= ${e2[t3]}) return constant;
        offset += k * ${n2[t3]};
        `;
            return `
      float padA(int m[${s2}]) {
        const float constant = float(${a2});
        int offset = 0;
        int k = 0;
        ${u2}
        vec2 coords = offsetToCoords(offset, ${r2}, ${i3});
        float value = getColorAsFloat(${t2.texture2D}(A, coords));
        return value;
      }
      `;
          }, h = (t2, e2, n2, r2, i3, o2) => {
            const a2 = e2.length;
            let s2 = "";
            for (let t3 = a2 - 1; t3 >= 0; --t3) s2 += `
        k = m[${t3}] - ${o2[t3]};
        if (k < 0) { k = -k; }
        {
          const int _2n_1 = ${2 * (e2[t3] - 1)};
          k = int( mod( float(k), float(_2n_1) ) ) ;
          if(k >= ${e2[t3]}) { k = _2n_1 - k; }
        }
        offset += k * ${n2[t3]};
        `;
            return `
      float padA(int m[${a2}]) {
        int offset = 0;
        int k = 0;
        ${s2}
        vec2 coords = offsetToCoords(offset, ${r2}, ${i3});
        float value = getColorAsFloat(${t2.texture2D}(A, coords));
        return value;
      }
      `;
          }, g = (t2, e2, n2, r2, i3, o2) => {
            const a2 = e2.length;
            let s2 = "";
            for (let t3 = a2 - 1; t3 >= 0; --t3) s2 += `
        k = m[${t3}] - ${o2[t3]};
        if (k < 0)  k = 0;
        if (k >= ${e2[t3]}) k = ${e2[t3] - 1};
        offset += k * ${n2[t3]};
      `;
            return `
      float padA(int m[${a2}]) {
        int offset = 0;
        int k = 0;
        ${s2}
        vec2 coords = offsetToCoords(offset, ${r2}, ${i3});
        float value = getColorAsFloat(${t2.texture2D}(A, coords));
        return value;
      }
      `;
          };
        }, 2143: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.globalMaxPool = e.parseMaxPoolAttributes = e.maxPool = e.parseGlobalAveragePoolAttributes = e.globalAveragePool = e.parseAveragePoolAttributes = e.averagePool = void 0;
          const r = n(246), i2 = n(2517), o = n(2039);
          e.averagePool = (t2, e2, n2) => {
            p(e2);
            const r2 = { name: "AveragePool", inputNames: ["X"], inputTypes: [o.TextureType.unpacked], cacheHint: n2.cacheKey };
            return [t2.run(Object.assign(Object.assign({}, r2), { get: () => a(e2, r2, false, n2) }), e2)];
          }, e.parseAveragePoolAttributes = (t2) => {
            const e2 = t2.attributes.getString("auto_pad", "NOTSET"), n2 = t2.attributes.getInt("ceil_mode", 0), i3 = 0 !== t2.attributes.getInt("count_include_pad", 0), o2 = t2.attributes.getInts("kernel_shape"), a2 = t2.attributes.getInts("strides", []), s2 = t2.attributes.getInts("pads", []);
            if (0 !== n2) throw new Error("using ceil() in shape computation is not yet supported for AveragePool");
            return (0, r.createAttributeWithCacheKey)({ autoPad: e2, ceilMode: n2, countIncludePad: i3, kernelShape: o2, strides: a2, pads: s2 });
          };
          const a = (t2, e2, n2, r2) => {
            const [a2, s2] = u(t2, r2, n2), c2 = i2.ShapeUtil.size(a2.kernelShape);
            let l2 = "";
            a2.countIncludePad ? l2 += `value /= float(${c2});` : l2 += `value /= float(${c2} - pad);`;
            const p2 = `
        ${f(t2[0].dims, a2, "value += _X(x);", l2, "0.0")}
      `;
            return Object.assign(Object.assign({}, e2), { output: { dims: s2, type: t2[0].type, textureType: o.TextureType.unpacked }, shaderSource: p2 });
          };
          e.globalAveragePool = (t2, e2, n2) => {
            p(e2);
            const r2 = { name: "GlobalAveragePool", inputNames: ["X"], inputTypes: [o.TextureType.unpacked], cacheHint: `${n2.countIncludePad}` };
            return [t2.run(Object.assign(Object.assign({}, r2), { get: () => a(e2, r2, true, n2) }), e2)];
          }, e.parseGlobalAveragePoolAttributes = (t2) => {
            const e2 = 0 !== t2.attributes.getInt("count_include_pad", 0);
            return (0, r.createAttributeWithCacheKey)({ autoPad: "", ceilMode: 0, countIncludePad: e2, kernelShape: [], strides: [], pads: [] });
          }, e.maxPool = (t2, e2, n2) => {
            p(e2);
            const r2 = { name: "MaxPool", inputNames: ["X"], inputTypes: [o.TextureType.unpacked], cacheHint: n2.cacheKey };
            return [t2.run(Object.assign(Object.assign({}, r2), { get: () => s(e2, r2, false, n2) }), e2)];
          }, e.parseMaxPoolAttributes = (t2) => {
            const e2 = t2.attributes.getString("auto_pad", "NOTSET"), n2 = t2.attributes.getInt("ceil_mode", 0), i3 = t2.attributes.getInts("kernel_shape"), o2 = t2.attributes.getInts("strides", []), a2 = t2.attributes.getInts("pads", []), s2 = t2.attributes.getInt("storage_order", 0), u2 = t2.attributes.getInts("dilations", []);
            if (0 !== s2) throw new Error("column major storage order is not yet supported for MaxPool");
            if (0 !== n2) throw new Error("using ceil() in shape computation is not yet supported for MaxPool");
            return (0, r.createAttributeWithCacheKey)({ autoPad: e2, ceilMode: n2, countIncludePad: false, kernelShape: i3, strides: o2, pads: a2, storageOrder: s2, dilations: u2 });
          };
          const s = (t2, e2, n2, r2) => {
            const [i3, a2] = u(t2, r2, n2), s2 = `
      ${f(t2[0].dims, i3, "\n      value = max(_X(x), value);\n    ", "", "-1e5")}
    `;
            return Object.assign(Object.assign({}, e2), { output: { dims: a2, type: t2[0].type, textureType: o.TextureType.unpacked }, shaderSource: s2 });
          }, u = (t2, e2, n2) => {
            const r2 = t2[0].dims.slice(), o2 = Object.hasOwnProperty.call(e2, "dilations"), a2 = e2.kernelShape.slice(), s2 = e2.strides.slice(), u2 = o2 ? e2.dilations.slice() : [], c2 = e2.pads.slice();
            i2.PoolConvUtil.adjustPoolAttributes(n2, r2, a2, s2, u2, c2);
            const l2 = i2.PoolConvUtil.computePoolOutputShape(n2, r2, s2, u2, a2, c2, e2.autoPad), p2 = Object.assign({}, e2);
            return o2 ? Object.assign(p2, { kernelShape: a2, strides: s2, pads: c2, dilations: u2, cacheKey: e2.cacheKey }) : Object.assign(p2, { kernelShape: a2, strides: s2, pads: c2, cacheKey: e2.cacheKey }), [p2, l2];
          }, c = { autoPad: "", ceilMode: 0, countIncludePad: false, kernelShape: [], strides: [], pads: [], storageOrder: 0, dilations: [], cacheKey: "" }, l = { name: "GlobalMaxPool", inputNames: ["X"], inputTypes: [o.TextureType.unpacked] };
          e.globalMaxPool = (t2, e2) => (p(e2), [t2.run(Object.assign(Object.assign({}, l), { get: () => s(e2, l, true, c) }), e2)]);
          const p = (t2) => {
            if (!t2 || 1 !== t2.length) throw new Error("Pool ops requires 1 input.");
            if ("float32" !== t2[0].type && "float64" !== t2[0].type) throw new Error("Invalid input type.");
          }, f = (t2, e2, n2, r2, o2) => {
            const a2 = t2.length;
            if (e2.kernelShape.length <= 2) {
              const i3 = e2.kernelShape[e2.kernelShape.length - 1], s2 = e2.strides[e2.strides.length - 1], u2 = e2.pads[e2.pads.length / 2 - 1], c2 = e2.pads[e2.pads.length - 1], l2 = t2[a2 - 1];
              let p2 = "", f2 = "", d2 = "";
              if (p2 = u2 + c2 !== 0 ? `
          for (int i = 0; i < ${i3}; i++) {
            x[${a2} - 1] = indices[${a2} - 1] * ${s2} - ${u2} + i;
            if (x[${a2} - 1] < 0 || x[${a2} - 1] >= ${l2}) {
              pad++;
              continue;
            }
            ${n2}
          }` : `
          for (int i = 0; i < ${i3}; i++) {
            x[${a2} - 1] = indices[${a2} - 1] * ${s2} - ${u2} + i;
            ${n2}
          }`, 2 === e2.kernelShape.length) {
                const n3 = e2.kernelShape[e2.kernelShape.length - 2], r3 = e2.strides[e2.strides.length - 2], o3 = e2.pads[e2.pads.length / 2 - 2], s3 = e2.pads[e2.pads.length - 2], u3 = t2[a2 - 2];
                f2 = o3 + s3 !== 0 ? `
            for (int j = 0; j < ${n3}; j++) {
              x[${a2} - 2] = indices[${a2} - 2] * ${r3} - ${o3} + j;
              if (x[${a2} - 2] < 0 || x[${a2} - 2] >= ${u3}) {
                pad+= ${i3};
                continue;
              }
          ` : `
            for (int j = 0; j < ${n3}; j++) {
              x[${a2} - 2] = indices[${a2} - 2] * ${r3} - ${o3} + j;
            `, d2 = "\n          }\n        ";
              }
              return `
        float process(int indices[${a2}]) {
          int x[${a2}];
          copyVec(indices, x);

          float value = ${o2};
          int pad = 0;
          ${f2}
          ${p2}
          ${d2}
          ${r2}
          return value;
        }
      `;
            }
            {
              const s2 = i2.ShapeUtil.size(e2.kernelShape), u2 = i2.ShapeUtil.computeStrides(e2.kernelShape), c2 = u2.length, l2 = e2.pads.length, p2 = h(c2), f2 = d(t2, "inputDims"), g = d(e2.pads, "pads"), b = d(u2, "kernelStrides"), m = d(e2.strides, "strides");
              let y = "";
              return y = e2.pads.reduce(((t3, e3) => t3 + e3)) ? `
            if (x[j] >= inputDims[j] || x[j] < 0) {
              pad++;
              isPad = true;
              break;
            }
          }
          if (!isPad) {
            ${n2}
          }` : `
          }
          ${n2}
        `, `
        ${p2}
        float process(int indices[${a2}]) {
          int x[${a2}];
          copyVec(indices, x);
          int offset[${c2}];
          int pads[${l2}];
          int inputDims[${a2}];
          int kernelStrides[${c2}];
          int strides[${c2}];
          ${g}
          ${f2}
          ${m}
          ${b}

          float value = ${o2};
          int pad = 0;
          bool isPad = false;
          for (int i = 0; i < ${s2}; i++) {
            offsetToIndices(i, kernelStrides, offset);
            isPad = false;
            for (int j = ${a2} - ${c2}; j < ${a2}; j++) {
              x[j] = indices[j] * strides[j - ${a2} + ${c2}]
                + offset[j - ${a2} + ${c2}] - pads[j - 2];
              ${y}
          }
          ${r2}

          return value;
        }
      `;
            }
          }, d = (t2, e2) => {
            let n2 = "";
            for (let r2 = 0; r2 < t2.length; r2++) n2 += `
      ${e2}[${r2}] = ${t2[r2]};
    `;
            return n2;
          }, h = (t2) => `
  void offsetToIndices(int offset, int[${t2}] strides, out int[${t2}] indices) {
    if (${t2} == 0) {
      return;
    }
    for (int i = 0; i < ${t2} - 1; ++i) {
      indices[i] = offset / strides[i];
      offset -= indices[i] * strides[i];
    }
    indices[${t2} - 1] = offset;
  }`;
        }, 4939: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.reduceLogSumSquare = e.reduceLogSum = e.reduceProd = e.reduceMin = e.reduceMax = e.reduceMean = e.reduceSum = e.parseReduceAttributes = void 0;
          const r = n(246), i2 = n(782), o = n(2517), a = n(2039), s = (t2, e2, n2, r2, i3) => {
            c(e2);
            const o2 = { name: r2, inputNames: ["A"], inputTypes: [a.TextureType.unpacked] };
            return [t2.run(Object.assign(Object.assign({}, o2), { cacheHint: n2.cacheKey, get: () => u(t2, e2, n2, r2, i3, o2) }), e2)];
          };
          e.parseReduceAttributes = (t2) => {
            const e2 = t2.attributes.getInts("axes", []), n2 = 1 === t2.attributes.getInt("keepdims", 1);
            return (0, r.createAttributeWithCacheKey)({ axes: e2, keepDims: n2 });
          };
          const u = (t2, e2, n2, r2, i3, s2) => {
            const u2 = [], c2 = e2[0].dims.length || 1, l = [], p = o.ShapeUtil.normalizeAxes(n2.axes, e2[0].dims.length), f = i3(e2, p);
            let d = f[1];
            for (let t3 = 0; t3 < e2[0].dims.length; t3++) p.indexOf(t3) >= 0 || 0 === p.length ? (n2.keepDims && u2.push(1), d = `
          for(int j${t3} = 0; j${t3} < ${e2[0].dims[t3]}; j${t3}++) {
            inputIdx[${t3}] = j${t3};
            ${d}
          }`) : (l.push(`inputIdx[${t3}] = outputIdx[${u2.length}];`), u2.push(e2[0].dims[t3]));
            const h = `
      float process(int outputIdx[${u2.length || 1}]) {
        float value;                 // final result
        int inputIdx[${c2}];      // addressing input data
        ${l.join("\n")}
        ${f[0]}       // init ops for reduce max/min
        ${d}
        ${f[2]}       // final computation for reduce mean
        return value;
      }`;
            return Object.assign(Object.assign({}, s2), { output: { dims: u2, type: e2[0].type, textureType: a.TextureType.unpacked }, shaderSource: h });
          }, c = (t2) => {
            if (!t2 || 1 !== t2.length) throw new Error("Reduce op requires 1 input.");
            if (-1 === i2.NUMBER_TYPES.indexOf(t2[0].type)) throw new Error("Invalid input type.");
          };
          e.reduceSum = (t2, e2, n2) => s(t2, e2, n2, "ReduceSum", (() => ["value = 0.0;", "value += _A(inputIdx);", ""])), e.reduceMean = (t2, e2, n2) => s(t2, e2, n2, "ReduceMean", ((t3, e3) => {
            let n3 = 1;
            for (let r2 = 0; r2 < t3[0].dims.length; r2++) (e3.indexOf(r2) >= 0 || 0 === e3.length) && (n3 *= t3[0].dims[r2]);
            return ["value = 0.0;", "value += _A(inputIdx);", `value /= ${n3}.;`];
          })), e.reduceMax = (t2, e2, n2) => s(t2, e2, n2, "ReduceMax", ((t3, e3) => {
            const n3 = [];
            for (let r2 = 0; r2 < t3[0].dims.length; r2++) (e3.indexOf(r2) >= 0 || 0 === e3.length) && n3.push(`inputIdx[${r2}] = 0;`);
            return [`${n3.join("\n")}
value = _A(inputIdx);`, "value = max(value, _A(inputIdx));", ""];
          })), e.reduceMin = (t2, e2, n2) => s(t2, e2, n2, "ReduceMin", ((t3, e3) => {
            const n3 = [];
            for (let r2 = 0; r2 < t3[0].dims.length; r2++) (e3.indexOf(r2) >= 0 || 0 === e3.length) && n3.push(`inputIdx[${r2}] = 0;`);
            return [`${n3.join("\n")}
value = _A(inputIdx);`, "value = min(value, _A(inputIdx));", ""];
          })), e.reduceProd = (t2, e2, n2) => s(t2, e2, n2, "ReduceProd", (() => ["value = 1.0;", "value *= _A(inputIdx);", ""])), e.reduceLogSum = (t2, e2, n2) => s(t2, e2, n2, "ReduceLogSum", (() => ["value = 0.0;", "value += _A(inputIdx);", "value = log(value);"])), e.reduceLogSumSquare = (t2, e2, n2) => s(t2, e2, n2, "ReduceLogSumSquare", (() => ["float t; value = 0.0;", "t = _A(inputIdx); value += t * t;", ""]));
        }, 7019: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.isReshapeCheap = e.processDims3D = e.createPackedReshape3DProgramInfoLoader = void 0;
          const r = n(2517), i2 = n(5060), o = n(2039), a = n(2827);
          e.createPackedReshape3DProgramInfoLoader = (t2, e2, n2) => {
            const s = ((t3) => ({ name: "Reshape (packed)", inputTypes: [o.TextureType.packed], inputNames: ["A"], cacheHint: `${t3}` }))(n2);
            return Object.assign(Object.assign({}, s), { get: () => ((t3, e3, n3, s2) => {
              const u = e3.dims, c = s2;
              let l = "";
              for (let t4 = 0; t4 < 4; t4++) {
                let e4 = "";
                switch (t4) {
                  case 0:
                    e4 = "outputCoords = rc;";
                    break;
                  case 1:
                    e4 = "outputCoords = ivec3(rc.x, rc.y+1, rc.z);";
                    break;
                  case 2:
                    e4 = "outputCoords = ivec3(rc.x, rc.y, rc.z+1);";
                    break;
                  case 3:
                    e4 = "outputCoords = ivec3(rc.x, rc.y+1, rc.z+1);";
                    break;
                  default:
                    throw new Error();
                }
                l += `
        ${e4}
        ${t4 > 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[${t4}] = getChannel(getA(inputRC.x, inputRC.y, inputRC.z), innerDims);

        ${t4 > 0 ? "}" : ""}
      `;
              }
              const p = (0, i2.getGlsl)(t3.session.backend.glContext.version), f = `
      ${(function(t4) {
                const e4 = r.ShapeUtil.computeStrides(t4), n4 = ["b", "r", "c"], i3 = "index";
                return `
    ivec3 inputCoordsFromReshapedOutCoords(int index) {
      ${e4.map(((t5, r2) => `int ${n4[r2]} = ${i3} / ${t5}; ${r2 === e4.length - 1 ? `int ${n4[r2 + 1]} = ${i3} - ${n4[r2]} * ${t5}` : `index -= ${n4[r2]} * ${t5}`};`)).join("")}
      return ivec3(b, r, c);
    }
  `;
              })(u)}
      ${(function(t4) {
                const e4 = r.ShapeUtil.computeStrides(t4);
                return `
  int getFlattenedIndex(ivec3 coords) {
    // reverse y, z order
    return coords.x * ${e4[0]} + coords.z * ${e4[1]} + coords.y;
  }
`;
              })(c)}
      ${(0, a.unpackFromChannel)()}

      void main() {
        ivec3 rc = getOutputCoords();

        vec4 result = vec4(0.0);

        ivec3 outputCoords;
        int rows = ${c[2]};
        int cols = ${c[1]};

        ${l}
        ${p.output} = result;
      }
    `;
              return Object.assign(Object.assign({}, n3), { output: { dims: c, type: e3.type, textureType: o.TextureType.packed }, shaderSource: f, hasMain: true });
            })(t2, e2, s, n2) });
          }, e.processDims3D = function(t2) {
            if (0 === t2.length) return [1, 1, 1];
            let e2 = 1;
            for (let n2 = 0; n2 < t2.length - 2; ++n2) e2 *= t2[n2];
            return [e2, t2.length > 1 ? t2[t2.length - 2] : 1, t2[t2.length - 1]];
          }, e.isReshapeCheap = function(t2, e2) {
            let n2 = false;
            return n2 = 0 === t2.length || 0 === e2.length || (t2.length < 2 || e2.length < 2 ? t2[t2.length - 1] === e2[e2.length - 1] : t2[t2.length - 1] === e2[e2.length - 1] && t2[t2.length - 2] === e2[e2.length - 2]), n2;
          };
        }, 718: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.reshape = void 0;
          const r = n(2517);
          e.reshape = (t2, e2) => {
            const n2 = r.ShapeUtil.calculateReshapedDims(e2[0].dims, e2[1].integerData);
            return t2.session.pack ? [t2.reshapePacked(e2[0], n2)] : [t2.reshapeUnpacked(e2[0], n2)];
          };
        }, 2268: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.parseResizeAttributesV11 = e.parseResizeAttributesV10 = e.resize = void 0;
          const r = n(5060), i2 = n(2039), o = n(9390), a = n(2827), s = n(9793), u = { name: "Resize", inputNames: ["A"], inputTypes: [i2.TextureType.packed] };
          e.resize = (t2, e2, n2) => ((0, s.validateInputs)(e2, n2), [t2.run(Object.assign(Object.assign({}, u), { cacheHint: n2.cacheKey, get: () => c(t2, e2, n2) }), e2)]), e.parseResizeAttributesV10 = (t2) => (0, s.parseUpsampleAttributes)(t2, 10), e.parseResizeAttributesV11 = (t2) => (0, s.parseUpsampleAttributes)(t2, 11);
          const c = (t2, e2, n2) => {
            const s2 = (0, r.getGlsl)(t2.session.backend.glContext.version), [c2, p2] = l(e2, n2);
            if (c2.every(((t3) => 1 === t3)) && "tf_crop_and_resize" !== n2.coordinateTransformMode) return Object.assign(Object.assign({}, u), { output: { dims: p2, type: e2[0].type, textureType: i2.TextureType.packed }, hasMain: true, shaderSource: `void main() {
                    vec4 v = ${s2.texture2D}(X, TexCoords);
                    ${s2.output} = v;
                }` });
            const f2 = p2.length;
            if (f2 < 2) throw new Error(`output dimension should be at least 2, but got ${f2}`);
            const d = p2[f2 - 2], h = p2[f2 - 1], g = e2[0].dims;
            if (f2 !== g.length) throw new Error(`output dimension should match input ${g.length}, but got ${f2}`);
            const b = g[f2 - 2], m = g[f2 - 1], y = c2[f2 - 2], _ = c2[f2 - 1];
            let v = "";
            if ("linear" !== n2.mode) throw new Error(`resize (packed) does not support mode: '${n2.mode}'`);
            switch (n2.coordinateTransformMode) {
              case "asymmetric":
                v = "\n                    vec4 getSourceFracIndex(ivec4 coords) {\n                        return vec4(coords) / scaleWHWH;\n                    }\n                ";
                break;
              case "half_pixel":
                v = "\n                    vec4 getSourceFracIndex(ivec4 coords) {\n                        return (vec4(coords) + 0.5) / scaleWHWH - 0.5;\n                    }\n                ";
                break;
              case "pytorch_half_pixel":
                v = `
                    vec4 getSourceFracIndex(ivec4 coords) {
                        vec4 fcoords = vec4(coords);
                        return vec4(
                            ${h}.0 > 1.0 ? (fcoords.x + 0.5) / scaleWHWH.x - 0.5 : 0.0,
                            ${d}.0 > 1.0 ? (fcoords.y + 0.5) / scaleWHWH.y - 0.5 : 0.0,
                            ${h}.0 > 1.0 ? (fcoords.z + 0.5) / scaleWHWH.z - 0.5 : 0.0,
                            ${d}.0 > 1.0 ? (fcoords.w + 0.5) / scaleWHWH.w - 0.5 : 0.0
                          );
                    }
                `;
                break;
              case "align_corners":
                v = `
                    vec4 getSourceFracIndex(ivec4 coords) {
                        vec4 resized = vec4(${h}.0 - 1.0, ${d}.0 - 1.0, ${h}.0 - 1.0,
                            ${d}.0 - 1.0);
                        vec4 original = vec4(${m}.0 - 1.0, ${b}.0 - 1.0, ${m}.0 - 1.0,
                            ${b}.0 - 1.0);
                        vec4 new_scale = original / resized;
                        return vec4(coords) * new_scale;
                    }
                `;
                break;
              default:
                throw new Error(`resize (packed) does not support coordinateTransformMode:                                 '${n2.coordinateTransformMode}'`);
            }
            const w = (0, o.getCoordsDataType)(f2), x = `
            const vec2 inputWH = vec2(${b}.0, ${m}.0);
            const vec4 scaleWHWH = vec4(float(${y}), float(${_}), float(${y}), float(${_}));
            ${(0, a.unpackFromChannel)()}
            ${v}
            float getAValue(int x10, int r, int c, int d) {
                return getChannel(getA(x10, r, c, d), vec2(c, d));
            }
            void main() {
                ${w} 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 < ${d - 1};
                bool hasNextCol = rc.z < ${h - 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);

                ${s2.output} = vec4(newValue);
            }
        `;
            return Object.assign(Object.assign({}, u), { output: { dims: p2, type: e2[0].type, textureType: i2.TextureType.packed }, hasMain: true, shaderSource: x });
          }, l = (t2, e2) => {
            const n2 = t2[0].dims;
            let r2, i3 = e2.scales;
            if (0 === i3.length) {
              const o3 = t2[e2.scalesInputIdx];
              if (o3 && 0 !== o3.size) {
                if (t2[e2.sizesInputIdx]) throw new Error("Only one of scales or sizes must be provided as input.");
                i3 = p(o3, e2.mode, e2.isResize);
              } else {
                const o4 = t2[e2.sizesInputIdx];
                if (!o4 || 0 === o4.size) throw new Error("Either scales or sizes MUST be provided as input.");
                r2 = Array.from(o4.integerData), i3 = f(r2, n2, e2.mode, e2.isResize);
              }
            } else if (t2[e2.sizesInputIdx]) throw new Error("Only one of scales or sizes must be provided as input.");
            const o2 = r2 || n2.map(((t3, e3) => Math.floor(t3 * i3[e3])));
            return [i3, o2];
          }, p = (t2, e2, n2) => {
            const r2 = Array.from(t2.floatData);
            return (0, s.scalesValidation)(r2, e2, n2), r2;
          }, f = (t2, e2, n2, r2) => {
            const i3 = e2.length, o2 = new Array(i3);
            for (let n3 = 0, r3 = i3; n3 < r3; n3++) if (0 === e2[n3]) {
              if (0 !== t2[n3]) throw new Error("Input dim is zero but required output dim is non-zero.");
              o2[n3] = 1;
            } else o2[n3] = t2[n3] / e2[n3];
            return (0, s.scalesValidation)(o2, n2, r2), o2;
          };
        }, 8117: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.shape = void 0;
          const r = n(9162);
          e.shape = (t2, e2) => (i2(e2), [new r.Tensor([e2[0].dims.length], "int32", void 0, void 0, new Int32Array(e2[0].dims))]);
          const i2 = (t2) => {
            if (!t2 || 1 !== t2.length) throw new Error("Shape requires 1 input.");
          };
        }, 2278: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.sliceV10 = e.parseSliceAttributes = e.slice = void 0;
          const r = n(246), i2 = n(782), o = n(2517), a = n(2039), s = { name: "Slice", inputNames: ["A"], inputTypes: [a.TextureType.unpacked] };
          e.slice = (t2, e2, n2) => (c(e2), [t2.run(Object.assign(Object.assign({}, s), { cacheHint: n2.cacheKey, get: () => u(t2, e2[0], n2) }), e2)]), e.parseSliceAttributes = (t2) => {
            const e2 = t2.attributes.getInts("starts"), n2 = t2.attributes.getInts("ends"), i3 = t2.attributes.getInts("axes", []);
            return (0, r.createAttributeWithCacheKey)({ starts: e2, ends: n2, axes: i3 });
          };
          const u = (t2, e2, n2) => {
            const r2 = 0 === n2.axes.length ? e2.dims.slice(0).map(((t3, e3) => e3)) : n2.axes, i3 = o.ShapeUtil.normalizeAxes(r2, e2.dims.length), u2 = n2.starts.map(((t3, n3) => t3 > e2.dims[i3[n3]] - 1 ? e2.dims[i3[n3]] : o.ShapeUtil.normalizeAxis(t3, e2.dims[i3[n3]]))), c2 = n2.ends.map(((t3, n3) => t3 > e2.dims[i3[n3]] - 1 ? e2.dims[i3[n3]] : o.ShapeUtil.normalizeAxis(t3, e2.dims[i3[n3]]))), l2 = e2.dims.slice(), p2 = [];
            for (let t3 = 0; t3 < i3.length; t3++) l2[i3[t3]] = c2[t3] - u2[t3], u2[t3] > 0 && p2.push(`outputIdx[${i3[t3]}] += ${u2[t3]};`);
            const f = `
      float process(int outputIdx[${l2.length}]) {
        ${p2.join("\n      ")}
        return _A(outputIdx);
      }`;
            return Object.assign(Object.assign({}, s), { output: { dims: l2, type: e2.type, textureType: a.TextureType.unpacked }, shaderSource: f });
          }, c = (t2) => {
            if (!t2 || 1 !== t2.length) throw new Error("Slice requires 1 input.");
            if (-1 === i2.NUMBER_TYPES.indexOf(t2[0].type)) throw new Error("Invalid input type.");
          };
          e.sliceV10 = (t2, e2) => {
            p(e2);
            const n2 = l(t2, e2);
            return [t2.run(Object.assign(Object.assign({}, s), { cacheHint: n2.cacheKey, get: () => u(t2, e2[0], n2) }), [e2[0]])];
          };
          const l = (t2, e2) => {
            if (!t2.session.isInitializer(e2[1].dataId) || !t2.session.isInitializer(e2[2].dataId) || e2.length >= 4 && !t2.session.isInitializer(e2[3].dataId) || e2.length >= 5 && !t2.session.isInitializer(e2[4].dataId)) throw new Error("dynamic slice attributes are not allowed");
            if (e2.length >= 5 && e2[4].integerData.some(((t3) => 1 !== t3))) throw new Error("currently non-1 steps is not supported for Slice");
            const n2 = Array.from(e2[1].integerData), r2 = Array.from(e2[2].integerData), i3 = e2.length >= 4 ? Array.from(e2[3].integerData) : [];
            return { starts: n2, ends: r2, axes: i3, cacheKey: `${i3};${n2};${r2}` };
          }, p = (t2) => {
            if (!t2 || t2.length < 3 || t2.length > 5) throw new Error("Invalid input number.");
            if ("int32" !== t2[1].type || 1 !== t2[1].dims.length) throw new Error("Invalid input type.");
            if ("int32" !== t2[2].type || 1 !== t2[2].dims.length) throw new Error("Invalid input type.");
            if (t2.length >= 4 && ("int32" !== t2[3].type || 1 !== t2[3].dims.length)) throw new Error("Invalid input type.");
            if (t2.length >= 5 && ("int32" !== t2[4].type || 1 !== t2[4].dims.length)) throw new Error("Invalid input type.");
          };
        }, 5524: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.softmaxV13 = e.parseSoftmaxAttributesV13 = e.parseSoftmaxAttributes = e.softmax = void 0;
          const r = n(246), i2 = n(2517), o = n(5060), a = n(2039), s = n(3738), u = { name: "SoftmaxComputeMax", inputNames: ["A"], inputTypes: [a.TextureType.unpacked] }, c = { name: "SoftmaxComputeScale", inputNames: ["A", "Max"], inputTypes: [a.TextureType.unpacked, a.TextureType.unpacked] }, l = { name: "SoftMax", inputNames: ["A", "Max", "Norm"], inputTypes: [a.TextureType.unpacked, a.TextureType.unpacked, a.TextureType.unpacked] };
          e.softmax = (t2, e2, n2) => {
            g(e2);
            const r2 = e2[0].dims.slice(), o2 = i2.ShapeUtil.normalizeAxis(n2.axis, r2.length), a2 = i2.ShapeUtil.sizeToDimension(r2, o2), s2 = i2.ShapeUtil.sizeFromDimension(r2, o2);
            return p(t2, e2, n2, a2, s2);
          }, e.parseSoftmaxAttributes = (t2) => (0, r.createAttributeWithCacheKey)({ axis: t2.attributes.getInt("axis", 1) }), e.parseSoftmaxAttributesV13 = (t2) => (0, r.createAttributeWithCacheKey)({ axis: t2.attributes.getInt("axis", -1) }), e.softmaxV13 = (t2, e2, n2) => {
            g(e2);
            const o2 = e2[0].dims.slice(), a2 = i2.ShapeUtil.normalizeAxis(n2.axis, o2.length), u2 = o2.length, c2 = a2 !== u2 - 1, l2 = [];
            let f2, d2 = [], h2 = [];
            c2 && (d2 = Array.from({ length: u2 }).map(((t3, e3) => e3)), d2[a2] = u2 - 1, d2[u2 - 1] = a2, d2.map(((t3) => l2.push(o2[t3]))), f2 = (0, r.createAttributeWithCacheKey)({ perm: d2 }), h2 = (0, s.transpose)(t2, e2, f2));
            const b = c2 ? i2.ShapeUtil.sizeToDimension(l2, u2 - 1) : i2.ShapeUtil.sizeToDimension(o2, u2 - 1), m = c2 ? i2.ShapeUtil.sizeFromDimension(l2, u2 - 1) : i2.ShapeUtil.sizeFromDimension(o2, u2 - 1), y = p(t2, c2 ? h2 : e2, n2, b, m);
            return c2 ? (0, s.transpose)(t2, y, f2) : y;
          };
          const p = (t2, e2, n2, r2, i3) => {
            const o2 = f(t2, e2[0], r2, i3, [r2]), a2 = t2.run(Object.assign(Object.assign({}, u), { cacheHint: n2.cacheKey, get: () => o2 }), e2), s2 = d(t2, e2[0], r2, i3, o2.output.dims, [r2]), p2 = t2.run(Object.assign(Object.assign({}, c), { cacheHint: n2.cacheKey, get: () => s2 }), [e2[0], a2]), g2 = h(t2, e2[0], r2, i3, o2.output.dims, s2.output.dims);
            return [t2.run(Object.assign(Object.assign({}, l), { cacheHint: n2.cacheKey, get: () => g2 }), [e2[0], a2, p2])];
          }, f = (t2, e2, n2, r2, i3) => {
            const [s2, c2] = t2.calculateTextureWidthAndHeight(e2.dims, a.TextureType.unpacked), l2 = i3.length;
            if (n2 < 1 || r2 < 1) throw new Error("Logical row count N and feature count D must be greater than or equal to 1");
            if (1 !== i3.length) throw new Error("Dimensionality of the output should be 1");
            if (i3[0] !== n2) throw new Error("Shape of the output should be equal to logical row count");
            const p2 = (0, o.getGlsl)(t2.session.backend.glContext.version), f2 = `
      float process(int[${l2}] indices) {
        int logical_row_start_offset = indices[0] * ${r2};

        float max = getColorAsFloat(${p2.texture2D}(A, offsetToCoords(logical_row_start_offset, ${s2},
        ${c2} )));
        for(int i=1; i<${r2}; ++i)
        {
          float current = getColorAsFloat(${p2.texture2D}(A, offsetToCoords(logical_row_start_offset + i,
            ${s2}, ${c2})));
          if(current > max)
          max = current;
        }

        return max;
      }`;
            return Object.assign(Object.assign({}, u), { output: { dims: i3, type: e2.type, textureType: a.TextureType.unpacked }, shaderSource: f2 });
          }, d = (t2, e2, n2, r2, i3, s2) => {
            const [u2, l2] = t2.calculateTextureWidthAndHeight(e2.dims, a.TextureType.unpacked), p2 = s2.length;
            if (n2 < 1 || r2 < 1) throw new Error("Logical row count N and feature count D must be greater than or equal to 1");
            if (1 !== s2.length) throw new Error("Dimensionality of the output should be 1");
            if (s2[0] !== n2) throw new Error("Shape of the output should be equal to logical row count");
            if (1 !== i3.length) throw new Error("Dimensionality of the intermediate results should be 1");
            if (i3[0] !== n2) throw new Error("Shape of the intermediate results should be equal to logical row count");
            const f2 = `
      float process(int[${p2}] indices) {
        int logical_row_start_offset = indices[0] * ${r2};

        float norm_factor = 0.0;
        float max = _Max(indices);
        for(int i=0; i<${r2}; ++i)
        {
          norm_factor += exp(getColorAsFloat(${(0, o.getGlsl)(t2.session.backend.glContext.version).texture2D}(A, offsetToCoords(logical_row_start_offset + i,
            ${u2}, ${l2}))) - max);
        }

        return norm_factor;
      }`;
            return Object.assign(Object.assign({}, c), { output: { dims: s2, type: e2.type, textureType: a.TextureType.unpacked }, shaderSource: f2 });
          }, h = (t2, e2, n2, r2, i3, o2) => {
            const [s2, u2] = t2.calculateTextureWidthAndHeight(e2.dims, a.TextureType.unpacked), c2 = e2.dims.length;
            if (n2 < 1 || r2 < 1) throw new Error("Logical row count N and feature count D must be greater than or equal to 1");
            if (1 !== i3.length || 1 !== o2.length) throw new Error("Dimensionality of the intermediate results should be 1");
            if (i3[0] !== n2 || o2[0] !== n2) throw new Error("Shape of the intermediate results should be equal to logical row count");
            const p2 = `
      float process(int[${c2}] indices) {

      // get offset of current logical tensor index from the 2-D texture coordinates (TexCoords)
      int offset = coordsToOffset(TexCoords, ${s2}, ${u2});

      //determine the logical row for this index
      int logical_row_index[1];
      logical_row_index[0] = offset / ${r2};

      float norm_factor = _Norm(logical_row_index);

      // avoid possible division by 0
      // if norm_facor is 0, all elements are zero
      // if so, return 0
      if(norm_factor == 0.0)
        return 0.0;

      return exp(_A(indices) - _Max(logical_row_index)) / norm_factor;
    }`;
            return Object.assign(Object.assign({}, l), { output: { dims: e2.dims, type: e2.type, textureType: a.TextureType.unpacked }, shaderSource: p2 });
          }, g = (t2) => {
            if (!t2 || 1 !== t2.length) throw new Error("Softmax requires 1 input.");
            if ("float32" !== t2[0].type && "float64" !== t2[0].type) throw new Error("Invalid input type");
          };
        }, 5975: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.parseSplitAttributes = e.split = void 0;
          const r = n(246), i2 = n(2517), o = n(2039), a = { name: "Split", inputNames: ["A"], inputTypes: [o.TextureType.unpacked] };
          e.split = (t2, e2, n2) => {
            c(e2);
            const r2 = i2.ShapeUtil.normalizeAxis(n2.axis, e2[0].dims.length), o2 = s(t2, e2, r2, n2), l = [];
            for (let i3 = 0; i3 < o2; ++i3) l.push(t2.run(Object.assign(Object.assign({}, a), { cacheHint: `${n2.cacheKey};${i3}`, get: () => u(t2, e2[0], n2, r2, i3) }), e2));
            return l;
          }, e.parseSplitAttributes = (t2) => {
            const e2 = t2.attributes.getInt("axis", 0), n2 = t2.attributes.getInts("split", []), i3 = t2.outputs.length;
            return (0, r.createAttributeWithCacheKey)({ axis: e2, split: n2, numOutputs: i3 });
          };
          const s = (t2, e2, n2, r2) => {
            const [, o2] = i2.SplitUtil.splitShape(e2[0].dims, n2, r2.split, r2.numOutputs);
            return o2.length;
          }, u = (t2, e2, n2, r2, s2) => {
            const [u2, c2] = i2.SplitUtil.splitShape(e2.dims, r2, n2.split, n2.numOutputs), l = c2[s2], p = u2[s2], f = `
      float process(int indices[${p.length}]) {
        indices[${r2}] += ${l};
        return _A(indices);
      }
    `;
            return Object.assign(Object.assign({}, a), { cacheHint: `${n2.cacheKey}:${s2}`, output: { dims: p, type: e2.type, textureType: o.TextureType.unpacked }, shaderSource: f });
          }, c = (t2) => {
            if (!t2 || 1 !== t2.length) throw new Error("Split requires one input.");
            if ("int8" !== t2[0].type && "uint8" !== t2[0].type && "int16" !== t2[0].type && "uint16" !== t2[0].type && "int32" !== t2[0].type && "uint32" !== t2[0].type && "float32" !== t2[0].type && "float64" !== t2[0].type && "bool" !== t2[0].type) throw new Error("Invalid input type.");
          };
        }, 3933: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.parseSqueezeAttributes = e.squeezeV13 = e.squeeze = void 0;
          const r = n(2517);
          e.squeeze = (t2, e2, n2) => {
            i2(e2);
            const o2 = r.ShapeUtil.squeezeShape(e2[0].dims, n2);
            return [t2.reshapeUnpacked(e2[0], o2)];
          }, e.squeezeV13 = (t2, n2) => (o(n2), (0, e.squeeze)(t2, [n2[0]], Array.from(n2[1].integerData))), e.parseSqueezeAttributes = (t2) => t2.attributes.getInts("axes");
          const i2 = (t2) => {
            if (!t2 || 1 !== t2.length) throw new Error("Squeeze requires 1 input.");
            if ("string" === t2[0].type) throw new Error("invalid input tensor types.");
          }, o = (t2) => {
            if (!t2 || 2 !== t2.length) throw new Error("Squeeze requires 2 inputs.");
            if ("int32" !== t2[1].type) throw new Error("Invalid input type.");
          };
        }, 6558: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.sum = void 0;
          const r = n(5060), i2 = n(2039);
          e.sum = (t2, e2) => {
            a(e2);
            const n2 = { name: "Sum", inputNames: e2.map(((t3, e3) => `X${e3}`)), inputTypes: new Array(e2.length).fill(i2.TextureType.unpacked) };
            return [t2.run(Object.assign(Object.assign({}, n2), { get: () => o(t2, e2, n2) }), e2)];
          };
          const o = (t2, e2, n2) => {
            const o2 = (0, r.getGlsl)(t2.session.backend.glContext.version), a2 = e2[0].dims.slice(), s = `
      void main() {
        vec4 result = ${e2.map(((t3, e3) => `${o2.texture2D}(X${e3},TexCoords)`)).join(" + ")};
        ${o2.output} = result;
      }
    `;
            return Object.assign(Object.assign({}, n2), { output: { dims: a2, type: e2[0].type, textureType: i2.TextureType.unpacked }, hasMain: true, shaderSource: s });
          }, a = (t2) => {
            if (!t2 || 0 === t2.length) throw new Error("Sum requires inputs.");
            const e2 = t2[0].dims.length;
            for (let n2 = 1; n2 < t2.length; n2++) {
              if (e2 !== t2[n2].dims.length) throw new Error("Input shapes are mismatched.");
              for (let r2 = 0; r2 < e2; r2++) if (t2[0].dims[r2] !== t2[n2].dims[r2]) throw new Error("Input shapes are not matched.");
            }
            if ("float32" !== t2[0].type && "float64" !== t2[0].type) throw new Error("Invalid input type.");
            for (let e3 = 1; e3 < t2.length; e3++) if (t2[0].type !== t2[e3].type) throw new Error("Input types are not matched.");
          };
        }, 5723: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.tile = void 0;
          const r = n(782), i2 = n(2039);
          e.tile = (t2, e2) => {
            a(e2);
            const n2 = { name: "Tile", inputNames: ["A"], inputTypes: [i2.TextureType.unpacked] };
            return [t2.run(Object.assign(Object.assign({}, n2), { get: () => o(t2, e2, n2) }), e2)];
          };
          const o = (t2, e2, n2) => {
            const r2 = e2[0].dims.slice(), o2 = new Array(r2.length), a2 = [];
            for (let t3 = 0; t3 < r2.length; t3++) o2[t3] = r2[t3] * e2[1].numberData[t3], a2.push(`inputIdx[${t3}] = int(mod(float(outputIdx[${t3}]), ${r2[t3]}.));`);
            const s = o2.length, u = `
      float process(int outputIdx[${s}]) {
        int inputIdx[${s}];
        ${a2.join("\n")}
        return _A(inputIdx);
      }
    `;
            return Object.assign(Object.assign({}, n2), { output: { dims: o2, type: e2[0].type, textureType: i2.TextureType.unpacked }, shaderSource: u });
          }, a = (t2) => {
            if (!t2 || 2 !== t2.length) throw new Error("Tile requires 2 input.");
            if (1 !== t2[1].dims.length) throw new Error("The second input shape must 1 dimension.");
            if (t2[1].dims[0] !== t2[0].dims.length) throw new Error("Invalid input shape.");
            if (-1 === r.NUMBER_TYPES.indexOf(t2[0].type)) throw new Error("Invalid input type.");
            if ("int32" !== t2[1].type && "int16" !== t2[1].type) throw new Error("Invalid repeat type.");
          };
        }, 3738: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.parseTransposeAttributes = e.transpose = void 0;
          const r = n(246), i2 = n(2517), o = n(2039), a = { name: "Transpose", inputNames: ["A"], inputTypes: [o.TextureType.unpacked] };
          e.transpose = (t2, e2, n2) => (p(e2), [t2.run(Object.assign(Object.assign({}, a), { cacheHint: n2.cacheKey, get: () => s(t2, e2[0], n2.perm) }), e2)]), e.parseTransposeAttributes = (t2) => (0, r.createAttributeWithCacheKey)({ perm: t2.attributes.getInts("perm", []) });
          const s = (t2, e2, n2) => {
            const r2 = e2.dims;
            n2 = u(r2, n2);
            const i3 = c(r2, n2), s2 = r2.length, p2 = `
      ${l("perm", n2, s2)}
      float process(int indices[${s2}]) {
        int a[${s2}];
        perm(a, indices);
        return _A(a);
      }`;
            return Object.assign(Object.assign({}, a), { output: { dims: i3, type: e2.type, textureType: o.TextureType.unpacked }, shaderSource: p2 });
          }, u = (t2, e2) => (e2 && e2.length !== t2.length && (e2 = [...t2.keys()].reverse()), e2), c = (t2, e2) => (e2 = u(t2, e2), i2.ShapeUtil.sortBasedOnPerm(t2, e2)), l = (t2, e2, n2) => {
            const r2 = [];
            r2.push(`void ${t2}(out int a[${n2}], int src[${n2}]) {`);
            for (let t3 = 0; t3 < n2; ++t3) r2.push(`	a[${e2[t3]}]=src[${t3}];`);
            return r2.push("	}"), r2.join("\n");
          }, p = (t2) => {
            if (!t2 || 1 !== t2.length) throw new Error("Transpose requires 1 input.");
            if ("float32" !== t2[0].type && "float64" !== t2[0].type) throw new Error("input should be float tensor");
          };
        }, 8710: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.encodeAsUint8 = void 0;
          const r = n(5060), i2 = n(2039);
          e.encodeAsUint8 = (t2, e2) => {
            const n2 = e2.shape, o = (0, r.getGlsl)(t2.session.backend.glContext.version), a = `
    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 = ${o.texture2D}(X,TexCoords).r;
      ${o.output} = encodeAsUint8(value);
    }`, s = { name: "Uint8Encode", inputTypes: [i2.TextureType.unpacked], inputNames: ["X"], output: { dims: n2, type: e2.tensor.type, textureType: i2.TextureType.downloadUint8AsFloat }, shaderSource: a, hasMain: true };
            return t2.executeProgram(s, [e2.tensor]);
          };
        }, 4909: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.tanh = e.tan = e.sqrt = e.sin = e.sigmoid = e.relu = e.not = e.neg = e.log = e.parseLeakyReluAttributes = e.leakyRelu = e.identity = e.floor = e.exp = e.parseEluAttributes = e.elu = e.cos = e.ceil = e.clipV11 = e.parseClipAttributes = e.clip = e.atan = e.asin = e.acos = e.abs = e.glslTanh = e.glslTan = e.glslSqrt = e.glslSigmoid = e.glslRelu = e.glslSin = e.glslNot = e.glslNeg = e.glslLog = e.glslLeakyRelu = e.glslIdentity = e.glslClip = e.glslFloor = e.glslExp = e.glslElu = e.glslCos = e.glslCeil = e.glslAtan = e.glslAsin = e.glslAcos = e.glslAbs = void 0;
          const r = n(246), i2 = n(2517), o = n(8520), a = n(5060), s = n(2039);
          function u() {
            return P("abs");
          }
          function c() {
            return P("acos");
          }
          function l() {
            return P("asin");
          }
          function p() {
            return P("atan");
          }
          function f() {
            return P("ceil");
          }
          function d() {
            return P("cos");
          }
          function h(t2) {
            const e2 = "elu";
            return { body: `
  const float alpha = float(${t2});

  float ${e2}_(float a) {
    return a >= 0.0 ? a: (exp(a) - 1.0) * alpha;
  }
  vec4 ${e2}_(vec4 v) {
    return vec4(${e2}_(v.x), ${e2}_(v.y), ${e2}_(v.z), ${e2}_(v.w));
  }
  `, name: e2, type: o.FunctionType.ValueBased };
          }
          function g() {
            return P("exp");
          }
          function b() {
            return P("floor");
          }
          function m(t2, e2) {
            const n2 = "clip";
            return { body: `
  const float min = float(${t2});
  const float max = float(${e2});

  float ${n2}_(float a) {
    return clamp(a, min, max);
  }
  vec4 ${n2}_(vec4 v) {
    return clamp(v, min, max);
  }
  `, name: n2, type: o.FunctionType.ValueBased };
          }
          function y() {
            const t2 = "indentity";
            return { body: `
  float ${t2}_(float a) {
    return a;
  }
  vec4 ${t2}_(vec4 v) {
    return v;
  }
  `, name: t2, type: o.FunctionType.ValueBased };
          }
          function _(t2) {
            const e2 = "leakyRelu";
            return { body: `
  const float alpha = float(${t2});

  float ${e2}_(float a) {
    return a < 0.0 ? a * alpha : a;
  }
  vec4 ${e2}_(vec4 v) {
    return vec4(${e2}_(v.x), ${e2}_(v.y), ${e2}_(v.z), ${e2}_(v.w));
  }
  `, name: e2, type: o.FunctionType.ValueBased };
          }
          function v() {
            return P("log");
          }
          function w() {
            const t2 = "neg";
            return { body: `
  float ${t2}_(float a) {
    return -a;
  }
  vec4 ${t2}_(vec4 v) {
    return -v;
  }
  `, name: t2, type: o.FunctionType.ValueBased };
          }
          function x() {
            const t2 = "not";
            return { body: `
  float ${t2}_(float a) {
    return float( ! bool(a) );
  }
  bool ${t2}_(bool a) {
    return !a;
  }
  vec4 ${t2}_(vec4 v) {
    return vec4(!bool(v.x), !bool(v.y), !bool(v.z), !bool(v.w));
  }
  bvec4 ${t2}_(bvec4 v) {
    return bvec4(!v.x, !v.y, !v.z, !v.w);
  }
  `, name: t2, type: o.FunctionType.ValueBased };
          }
          function T() {
            return P("sin");
          }
          function S() {
            const t2 = "relu";
            return { body: `
  float ${t2}_(float a) {
    return max( a, 0.0 );
  }
  vec4 ${t2}_(vec4 v) {
    return max( v, 0.0 );
  }
  `, name: t2, type: o.FunctionType.ValueBased };
          }
          function O() {
            const t2 = "sigmoid";
            return { body: `
  float ${t2}_(float a) {
    return 1.0 / (1.0 + exp(-a));
  }
  vec4 ${t2}_(vec4 v) {
    return 1.0 / (1.0 + exp(-v));
  }
  `, name: t2, type: o.FunctionType.ValueBased };
          }
          function A() {
            return P("sqrt");
          }
          function E() {
            return P("tan");
          }
          function I() {
            const t2 = "tanh";
            return { body: `
  float ${t2}_(float a) {
    a = clamp(a, -10., 10.);
    a = exp(2.*a);
    return (a - 1.) / (a + 1.);
  }
  vec4 ${t2}_(vec4 v) {
    v = clamp(v, -10., 10.);
    v = exp(2.*v);
    return (v - 1.) / (v + 1.);
  }
  `, name: t2, type: o.FunctionType.ValueBased };
          }
          function P(t2) {
            return { body: `
  float ${t2}_(float a) {
    return ${t2}(a);
  }
  vec4 ${t2}_(vec4 v) {
    return ${t2}(v);
  }
  `, name: t2, type: o.FunctionType.ValueBased };
          }
          e.glslAbs = u, e.glslAcos = c, e.glslAsin = l, e.glslAtan = p, e.glslCeil = f, e.glslCos = d, e.glslElu = h, e.glslExp = g, e.glslFloor = b, e.glslClip = m, e.glslIdentity = y, e.glslLeakyRelu = _, e.glslLog = v, e.glslNeg = w, e.glslNot = x, e.glslSin = T, e.glslRelu = S, e.glslSigmoid = O, e.glslSqrt = A, e.glslTan = E, e.glslTanh = I;
          const D = (t2, e2, n2, r2) => {
            const i3 = t2.session.pack ? s.TextureType.packed : s.TextureType.unpacked, o2 = { name: n2.name, inputTypes: [i3], inputNames: ["A"], cacheHint: r2 };
            return Object.assign(Object.assign({}, o2), { get: () => ((t3, e3, n3, r3) => {
              const i4 = t3.session.pack ? s.TextureType.packed : s.TextureType.unpacked, o3 = (0, a.getGlsl)(t3.session.backend.glContext.version);
              return Object.assign(Object.assign({}, e3), { output: { dims: n3.dims, type: n3.type, textureType: i4 }, shaderSource: `
     ${r3.body}
     void main() {
       vec4 v = ${o3.texture2D}(A, TexCoords);
       v = ${r3.name}_(v);
       ${o3.output} = v;
     }
     `, hasMain: true });
            })(t2, o2, e2, n2) });
          };
          e.abs = (t2, e2) => [t2.run(D(t2, e2[0], u()), e2)], e.acos = (t2, e2) => [t2.run(D(t2, e2[0], c()), e2)], e.asin = (t2, e2) => [t2.run(D(t2, e2[0], l()), e2)], e.atan = (t2, e2) => [t2.run(D(t2, e2[0], p()), e2)], e.clip = (t2, e2, n2) => [t2.run(D(t2, e2[0], m(n2.min, n2.max), n2.cacheKey), e2)], e.parseClipAttributes = (t2) => (0, r.createAttributeWithCacheKey)({ min: t2.attributes.getFloat("min", i2.MIN_CLIP), max: t2.attributes.getFloat("max", i2.MAX_CLIP) }), e.clipV11 = (t2, n2) => {
            const r2 = $(t2, n2);
            return (0, e.clip)(t2, [n2[0]], r2);
          };
          const $ = (t2, e2) => {
            if (e2.length >= 3 && (!t2.session.isInitializer(e2[1].dataId) || !t2.session.isInitializer(e2[2].dataId))) throw new Error("dynamic clip attributes are not allowed");
            const n2 = e2.length >= 3 ? e2[1].numberData[0] : i2.MIN_CLIP, o2 = e2.length >= 3 ? e2[2].numberData[0] : i2.MAX_CLIP;
            return (0, r.createAttributeWithCacheKey)({ min: n2, max: o2 });
          };
          e.ceil = (t2, e2) => [t2.run(D(t2, e2[0], f()), e2)], e.cos = (t2, e2) => [t2.run(D(t2, e2[0], d()), e2)], e.elu = (t2, e2, n2) => [t2.run(D(t2, e2[0], h(n2.alpha), n2.cacheKey), e2)], e.parseEluAttributes = (t2) => (0, r.createAttributeWithCacheKey)({ alpha: t2.attributes.getFloat("alpha", 1) }), e.exp = (t2, e2) => [t2.run(D(t2, e2[0], g()), e2)], e.floor = (t2, e2) => [t2.run(D(t2, e2[0], b()), e2)], e.identity = (t2, e2) => [t2.run(D(t2, e2[0], y()), e2)], e.leakyRelu = (t2, e2, n2) => [t2.run(D(t2, e2[0], _(n2.alpha), n2.cacheKey), e2)], e.parseLeakyReluAttributes = (t2) => (0, r.createAttributeWithCacheKey)({ alpha: t2.attributes.getFloat("alpha", 0.01) }), e.log = (t2, e2) => [t2.run(D(t2, e2[0], v()), e2)], e.neg = (t2, e2) => [t2.run(D(t2, e2[0], w()), e2)], e.not = (t2, e2) => [t2.run(D(t2, e2[0], x()), e2)], e.relu = (t2, e2) => [t2.run(D(t2, e2[0], S()), e2)], e.sigmoid = (t2, e2) => [t2.run(D(t2, e2[0], O()), e2)], e.sin = (t2, e2) => [t2.run(D(t2, e2[0], T()), e2)], e.sqrt = (t2, e2) => [t2.run(D(t2, e2[0], A()), e2)], e.tan = (t2, e2) => [t2.run(D(t2, e2[0], E()), e2)], e.tanh = (t2, e2) => [t2.run(D(t2, e2[0], I()), e2)];
        }, 5611: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.createUnpackProgramInfoLoader = e.createUnpackProgramInfo = void 0;
          const r = n(5060), i2 = n(2039), o = n(9390), a = n(2827), s = { name: "unpack", inputNames: ["A"], inputTypes: [i2.TextureType.packed] };
          e.createUnpackProgramInfo = (t2, e2) => {
            const n2 = e2.dims.length, u = (0, a.getChannels)("rc", n2), c = u.slice(-2), l = (0, o.getCoordsDataType)(n2), p = (0, a.unpackFromChannel)(), f = 0 === e2.dims.length ? "" : (function(t3, e3) {
              if (1 === t3) return "rc";
              let n3 = "";
              for (let r2 = 0; r2 < t3; r2++) n3 += e3[r2], r2 < t3 - 1 && (n3 += ",");
              return n3;
            })(n2, u), d = n2 <= 1 ? "rc" : `vec2(${c.join(",")})`, h = `
    ${p}
    void main() {
      ${l} rc = getOutputCoords();

       // Sample the texture with the coords to get the rgba channel value.
       vec4 packedInput = getA(${f});

       ${(0, r.getGlsl)(t2.session.backend.glContext.version).output} = vec4(getChannel(packedInput, ${d}), 0, 0, 0);
     }
   `;
            return Object.assign(Object.assign({}, s), { hasMain: true, output: { dims: e2.dims, type: e2.type, textureType: i2.TextureType.unpacked }, shaderSource: h });
          }, e.createUnpackProgramInfoLoader = (t2, n2) => Object.assign(Object.assign({}, s), { get: () => (0, e.createUnpackProgramInfo)(t2, n2) });
        }, 8428: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.parseUnsqueezeAttributes = e.unsqueezeV13 = e.unsqueeze = void 0;
          const r = n(2517);
          e.unsqueeze = (t2, e2, n2) => {
            i2(e2);
            const o2 = r.ShapeUtil.unsqueezeShape(e2[0].dims, n2);
            return [t2.reshapeUnpacked(e2[0], o2)];
          }, e.unsqueezeV13 = (t2, n2) => (o(n2), (0, e.unsqueeze)(t2, [n2[0]], Array.from(n2[1].integerData))), e.parseUnsqueezeAttributes = (t2) => t2.attributes.getInts("axes");
          const i2 = (t2) => {
            if (!t2 || 1 !== t2.length) throw new Error("Unsqueeze requires 1 input.");
            if ("string" === t2[0].type) throw new Error("invalid input tensor types.");
          }, o = (t2) => {
            if (!t2 || 2 !== t2.length) throw new Error("Unsqueeze requires 2 inputs.");
            if ("int32" !== t2[1].type) throw new Error("Invalid input type.");
          };
        }, 9793: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.scalesValidation = e.validateInputs = e.parseUpsampleAttributes = e.parseUpsampleAttributesV9 = e.parseUpsampleAttributesV7 = e.upsample = void 0;
          const r = n(246), i2 = n(5060), o = n(2039), a = { name: "Upsample", inputNames: ["X"], inputTypes: [o.TextureType.unpacked] };
          e.upsample = (t2, n2, r2) => ((0, e.validateInputs)(n2, r2), [t2.run(Object.assign(Object.assign({}, a), { cacheHint: r2.cacheKey, get: () => s(t2, n2, r2) }), n2)]), e.parseUpsampleAttributesV7 = (t2) => (0, e.parseUpsampleAttributes)(t2, 7), e.parseUpsampleAttributesV9 = (t2) => (0, e.parseUpsampleAttributes)(t2, 9), e.parseUpsampleAttributes = (t2, n2) => {
            const i3 = n2 >= 10, o2 = t2.attributes.getString("mode", "nearest");
            if ("nearest" !== o2 && "linear" !== o2 && (n2 < 11 || "cubic" !== o2)) throw new Error(`unrecognized mode: ${o2}`);
            let a2 = [];
            n2 < 9 && (a2 = t2.attributes.getFloats("scales"), (0, e.scalesValidation)(a2, o2, i3));
            const s2 = t2.attributes.getFloat("extrapolation_value", 0), u = n2 > 10 ? t2.attributes.getString("coordinate_transformation_mode", "half_pixel") : "asymmetric";
            if (-1 === ["asymmetric", "pytorch_half_pixel", "tf_half_pixel_for_nn", "align_corners", "tf_crop_and_resize", "half_pixel"].indexOf(u)) throw new Error(`coordinate_transform_mode '${u}' is not supported`);
            const c = "tf_crop_and_resize" === u, l = c, p = "nearest" === o2 && n2 >= 11 ? t2.attributes.getString("nearest_mode", "round_prefer_floor") : "";
            if (-1 === ["round_prefer_floor", "round_prefer_ceil", "floor", "ceil", ""].indexOf(p)) throw new Error(`nearest_mode '${p}' is not supported`);
            const f = t2.attributes.getFloat("cubic_coeff_a", -0.75), d = 0 !== t2.attributes.getInt("exclude_outside", 0);
            if (d && "cubic" !== o2) throw new Error("exclude_outside can be set to 1 only when mode is CUBIC.");
            const h = n2 < 11 || "nearest" === o2 && "asymmetric" === u && "floor" === p;
            let g = 0, b = 0, m = 0;
            return n2 > 10 ? t2.inputs.length > 2 ? (g = 1, b = 2, m = 3) : (b = 1, m = 2) : 9 === n2 && (b = 1), (0, r.createAttributeWithCacheKey)({ opset: n2, isResize: i3, mode: o2, scales: a2, extrapolationValue: s2, coordinateTransformMode: u, useExtrapolation: l, needRoiInput: c, nearestMode: p, cubicCoefficientA: f, excludeOutside: d, useNearest2xOptimization: h, roiInputIdx: g, scalesInputIdx: b, sizesInputIdx: m });
          };
          const s = (t2, e2, n2) => {
            const r2 = (0, i2.getGlsl)(t2.session.backend.glContext.version), [s2, u] = t2.calculateTextureWidthAndHeight(e2[0].dims, o.TextureType.unpacked), c = e2[0].dims.map(((t3, e3) => Math.floor(t3 * n2.scales[e3]))), [l, p] = t2.calculateTextureWidthAndHeight(c, o.TextureType.unpacked), f = c.length, d = new Array(f), h = new Array(f);
            let g = `
      int output_pitches[${f}];
      int input_pitches[${f}];
      `;
            for (let t3 = f - 1; t3 >= 0; t3--) d[t3] = t3 === f - 1 ? 1 : d[t3 + 1] * c[t3 + 1], h[t3] = t3 === f - 1 ? 1 : h[t3 + 1] * e2[0].dims[t3 + 1], g += `
        output_pitches[${t3}] = ${d[t3]};
        input_pitches[${t3}] = ${h[t3]};
        `;
            const b = `
      float getInputFloat(int index) {
        vec2 coords = offsetToCoords(index, ${s2}, ${u});
        float value = getColorAsFloat(${r2.texture2D}(X, coords));
        return value;
      }
      `, m = "nearest" === n2.mode ? `
    ${b}
    float process(int indices[${f}]) {
      int input_index = 0;
      int output_index = coordsToOffset(TexCoords, ${l}, ${p});

      ${g}

      int d, m;
      for (int dim = 0; dim < ${f}; ++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);
    }` : 4 === f ? `
    ${b}
    float process(int indices[4]) {
      int input_index = 0;
      int output_index = coordsToOffset(TexCoords, ${l}, ${p});

      ${g}

      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 == (${e2[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]);
    }` : `
    ${b}
    float process(int indices[2]) {
      int input_index = 0;
      int output_index = coordsToOffset(TexCoords, ${l}, ${p});

      ${g}

      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 == (${e2[0].dims[0]} - 1)) {
        // It's the end in dimension 0
        x01 = x00;
        end_of_dim0 = true;
      } else {
        x01 = getInputFloat(input_index + input_pitches[0]);
      }

      if (index_of_input_dim1 == (input_pitches[0] - 1)) {
        // It's the end in dimension 1
        x10 = x00;
        x11 = x01;
      }
      else {
        x10 = getInputFloat(input_index + 1);
        x11 = end_of_dim0 ? x10 : getInputFloat(input_index + input_pitches[0] + 1);
      }

      float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[0]);
      float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[0]);
      return y0 + float(x_offset) * (y1 - y0) / float(scales[1]);
    }`;
            return Object.assign(Object.assign({}, a), { output: { dims: c, type: e2[0].type, textureType: o.TextureType.unpacked }, shaderSource: m, variables: [{ name: "scales", type: "int", arrayLength: n2.scales.length, data: n2.scales.map(((t3) => Math.ceil(t3))) }] });
          };
          e.validateInputs = (t2, e2) => {
            if (!t2 || e2.opset < 9 && 1 !== t2.length || e2.opset >= 9 && e2.opset < 11 && 2 !== t2.length || e2.opset >= 11 && t2.length < 2) throw new Error("invalid inputs.");
            if (e2.scales.length > 0 && t2[0].dims.length !== e2.scales.length) throw new Error("Invalid input shape.");
            if ("string" === t2[0].type) throw new Error("Invalid input tensor types.");
          }, e.scalesValidation = (t2, e2, n2) => {
            if (n2) {
              for (const e3 of t2) if (e3 <= 0) throw new Error("Scale value should be greater than 0.");
            } else for (const e3 of t2) if (e3 < 1) throw new Error("Scale value should be greater than or equal to 1.");
            if (!("linear" !== e2 && "cubic" !== e2 || 2 === t2.length || 4 === t2.length && 1 === t2[0] && 1 === t2[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 ${n2 ? "Resize" : "Upsample"} opeartor.`);
          };
        }, 1958: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.ProgramManager = void 0;
          const r = n(1670), i2 = n(6231), o = n(8879), a = n(5060);
          e.ProgramManager = class {
            constructor(t2, e2, n2) {
              this.profiler = t2, this.glContext = e2, this.textureLayoutStrategy = n2, this.repo = /* @__PURE__ */ new Map(), this.attributesBound = false;
            }
            getArtifact(t2) {
              return this.repo.get(t2);
            }
            setArtifact(t2, e2) {
              this.repo.set(t2, e2);
            }
            run(t2, e2, n2) {
              var r2;
              this.profiler.event("op", `ProgramManager.run ${null !== (r2 = t2.programInfo.name) && void 0 !== r2 ? r2 : "unknown kernel"}`, (() => {
                var r3;
                const o2 = this.glContext.gl, a2 = t2.program;
                o2.useProgram(a2);
                try {
                  this.bindOutput(n2), this.attributesBound || this.bindAttributes(t2.attribLocations), this.bindUniforms(t2.uniformLocations, null !== (r3 = t2.programInfo.variables) && void 0 !== r3 ? r3 : [], e2);
                } catch (e3) {
                  throw i2.Logger.error("ProgramManager", t2.programInfo.shaderSource), e3;
                }
                this.profiler.event("backend", "GlContext.draw()", (() => {
                  this.glContext.draw();
                }));
              }), this.glContext);
            }
            dispose() {
              this.vertexShader && this.glContext.deleteShader(this.vertexShader), this.repo.forEach(((t2) => this.glContext.deleteProgram(t2.program)));
            }
            build(t2, e2, n2) {
              return this.profiler.event("backend", "ProgramManager.build", (() => {
                const r2 = new o.GlslPreprocessor(this.glContext, t2, e2, n2), i3 = r2.preprocess(), a2 = this.compile(i3);
                return { programInfo: t2, program: a2, uniformLocations: this.getUniformLocations(a2, r2.context.programInfo.inputNames, r2.context.programInfo.variables), attribLocations: this.getAttribLocations(a2) };
              }));
            }
            compile(t2) {
              if (!this.vertexShader) {
                i2.Logger.verbose("ProrgramManager", "Compiling and caching Vertex shader for the first time");
                const t3 = (0, a.getVertexShaderSource)(this.glContext.version);
                this.vertexShader = this.glContext.compileShader(t3, this.glContext.gl.VERTEX_SHADER);
              }
              r.env.debug && i2.Logger.verbose("ProrgramManager", `FragShader:
${t2}
`);
              const e2 = this.glContext.compileShader(t2, this.glContext.gl.FRAGMENT_SHADER), n2 = this.glContext.createProgram(this.vertexShader, e2);
              return this.glContext.deleteShader(e2), n2;
            }
            bindOutput(t2) {
              const e2 = t2.width, n2 = t2.height;
              i2.Logger.verbose("ProrgramManager", `Binding output texture to Framebuffer: w/h=${e2}/${n2}, shape=${t2.shape}, type=${t2.tensor.type}`), this.glContext.attachFramebuffer(t2.texture, e2, n2);
            }
            bindAttributes(t2) {
              const e2 = t2.position, n2 = t2.textureCoord;
              this.glContext.setVertexAttributes(e2, n2), this.attributesBound = true;
            }
            bindUniforms(t2, e2, n2) {
              var r2;
              const i3 = this.glContext.gl;
              let o2 = 0;
              for (const { name: a2, type: s, location: u, arrayLength: c } of t2) {
                const t3 = null === (r2 = e2.find(((t4) => t4.name === a2))) || void 0 === r2 ? void 0 : r2.data;
                if ("sampler2D" !== s && !t3) throw new Error(`variable '${a2}' does not have data defined in program info`);
                switch (s) {
                  case "sampler2D":
                    this.bindTexture(n2[o2], u, o2), o2++;
                    break;
                  case "float":
                    c ? i3.uniform1fv(u, t3) : i3.uniform1f(u, t3);
                    break;
                  case "int":
                    c ? i3.uniform1iv(u, t3) : i3.uniform1i(u, t3);
                    break;
                  default:
                    throw new Error(`Uniform not implemented: ${s}`);
                }
              }
            }
            bindTexture(t2, e2, n2) {
              this.glContext.bindTextureToUniform(t2.texture, n2, e2);
            }
            getAttribLocations(t2) {
              return { position: this.getAttribLocation(t2, "position"), textureCoord: this.getAttribLocation(t2, "textureCoord") };
            }
            getUniformLocations(t2, e2, n2) {
              const r2 = [];
              if (e2) for (const n3 of e2) r2.push({ name: n3, type: "sampler2D", location: this.getUniformLocation(t2, n3) });
              if (n2) for (const e3 of n2) r2.push(Object.assign(Object.assign({}, e3), { location: this.getUniformLocation(t2, e3.name) }));
              return r2;
            }
            getUniformLocation(t2, e2) {
              const n2 = this.glContext.gl.getUniformLocation(t2, e2);
              if (null === n2) throw new Error(`Uniform ${e2} not found.`);
              return n2;
            }
            getAttribLocation(t2, e2) {
              return this.glContext.gl.getAttribLocation(t2, e2);
            }
          };
        }, 6416: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.WebGLSessionHandler = void 0;
          const r = n(6231), i2 = n(1047), o = n(8316), a = n(1640), s = n(1958), u = n(7859), c = n(5702);
          e.WebGLSessionHandler = class {
            constructor(t2, e2) {
              this.backend = t2, this.context = e2, this.layoutStrategy = new u.PreferLogicalStrategy(t2.glContext.maxTextureSize), this.programManager = new s.ProgramManager(this.context.profiler, t2.glContext, this.layoutStrategy), this.textureManager = new c.TextureManager(t2.glContext, this.layoutStrategy, this.context.profiler, { reuseTextures: "full" === t2.textureCacheMode }), this.packedTextureDataCache = /* @__PURE__ */ new Map(), this.unpackedTextureDataCache = /* @__PURE__ */ new Map(), this.pack = t2.pack, this.pack2unpackMap = /* @__PURE__ */ new Map(), this.unpack2packMap = /* @__PURE__ */ new Map();
            }
            createInferenceHandler() {
              return new o.WebGLInferenceHandler(this);
            }
            onGraphInitialized(t2) {
              const e2 = t2.getValues().filter(((t3) => -1 === t3.from && t3.tensor)).map(((t3) => t3.tensor.dataId));
              this.initializers = new Set(e2);
            }
            isInitializer(t2) {
              return !!this.initializers && this.initializers.has(t2);
            }
            addInitializer(t2) {
              this.initializers.add(t2);
            }
            getTextureData(t2, e2) {
              return e2 ? this.packedTextureDataCache.get(t2) : this.unpackedTextureDataCache.get(t2);
            }
            setTextureData(t2, e2, n2 = false) {
              r.Logger.verbose("WebGLSessionHandler", "Storing Texture data in cache"), n2 ? this.packedTextureDataCache.set(t2, e2) : this.unpackedTextureDataCache.set(t2, e2);
            }
            dispose() {
              this.programManager.dispose(), this.textureManager.clearActiveTextures(), this.packedTextureDataCache.forEach(((t2) => this.textureManager.releaseTexture(t2, true))), this.packedTextureDataCache = /* @__PURE__ */ new Map(), this.unpackedTextureDataCache.forEach(((t2) => this.textureManager.releaseTexture(t2, true))), this.unpackedTextureDataCache = /* @__PURE__ */ new Map();
            }
            resolve(t2, e2, n2) {
              const r2 = (0, i2.resolveOperator)(t2, e2, a.WEBGL_OP_RESOLVE_RULES);
              return { impl: r2.opImpl, context: r2.opInit ? r2.opInit(t2, n2) : t2 };
            }
          };
        }, 7769: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.Uint8DataEncoder = e.RGBAFloatDataEncoder = e.RedFloat32DataEncoder = void 0;
          const r = n(6231);
          e.RedFloat32DataEncoder = class {
            constructor(t2, e2 = 1) {
              if (1 === e2) this.internalFormat = t2.R32F, this.format = t2.RED, this.textureType = t2.FLOAT, this.channelSize = e2;
              else {
                if (4 !== e2) throw new Error(`Invalid number of channels: ${e2}`);
                this.internalFormat = t2.RGBA32F, this.format = t2.RGBA, this.textureType = t2.FLOAT, this.channelSize = e2;
              }
            }
            encode(t2, e2) {
              let n2, i2;
              return t2.constructor !== Float32Array && (r.Logger.warning("Encoder", "data was not of type Float32; creating new Float32Array"), i2 = new Float32Array(t2)), e2 * this.channelSize > t2.length ? (r.Logger.warning("Encoder", "Source data too small. Allocating larger array"), i2 = t2, n2 = this.allocate(e2 * this.channelSize), i2.forEach(((t3, e3) => n2[e3] = t3))) : (i2 = t2, n2 = i2), n2;
            }
            allocate(t2) {
              return new Float32Array(4 * t2);
            }
            decode(t2, e2) {
              return 1 === this.channelSize ? t2.filter(((t3, e3) => e3 % 4 == 0)).subarray(0, e2) : t2.subarray(0, e2);
            }
          }, e.RGBAFloatDataEncoder = class {
            constructor(t2, e2 = 1, n2) {
              if (1 !== e2 && 4 !== e2) throw new Error(`Invalid number of channels: ${e2}`);
              this.internalFormat = t2.RGBA, this.format = t2.RGBA, this.channelSize = e2, this.textureType = n2 || t2.FLOAT;
            }
            encode(t2, e2) {
              let n2 = t2;
              return 1 === this.channelSize && (r.Logger.verbose("Encoder", "Exploding into a larger array"), n2 = this.allocate(e2), t2.forEach(((t3, e3) => n2[4 * e3] = t3))), n2;
            }
            allocate(t2) {
              return new Float32Array(4 * t2);
            }
            decode(t2, e2) {
              return 1 === this.channelSize ? t2.filter(((t3, e3) => e3 % 4 == 0)).subarray(0, e2) : t2.subarray(0, e2);
            }
          }, e.Uint8DataEncoder = class {
            constructor(t2, e2 = 1) {
              if (this.channelSize = 4, 1 === e2) this.internalFormat = t2.ALPHA, this.format = t2.ALPHA, this.textureType = t2.UNSIGNED_BYTE, this.channelSize = e2;
              else {
                if (4 !== e2) throw new Error(`Invalid number of channels: ${e2}`);
                this.internalFormat = t2.RGBA, this.format = t2.RGBA, this.textureType = t2.UNSIGNED_BYTE, this.channelSize = e2;
              }
            }
            encode(t2, e2) {
              return new Uint8Array(t2.buffer, t2.byteOffset, t2.byteLength);
            }
            allocate(t2) {
              return new Uint8Array(t2 * this.channelSize);
            }
            decode(t2, e2) {
              if (t2 instanceof Uint8Array) return t2.subarray(0, e2);
              throw new Error(`Invalid array type: ${t2.constructor}`);
            }
          };
        }, 7859: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.getBatchDim = e.sizeToSquarishShape = e.getRowsCols = e.sizeFromShape = e.isInt = e.parseAxisParam = e.squeezeShape = e.PreferLogicalStrategy = e.AlwaysKeepOriginalSizeStrategy = void 0;
          const r = n(6231), i2 = n(2517);
          function o(t2, e2) {
            const n2 = [], r2 = [], i3 = null != e2 && Array.isArray(e2) && 0 === e2.length, o2 = null == e2 || i3 ? null : a(e2, t2).sort();
            let s2 = 0;
            for (let e3 = 0; e3 < t2.length; ++e3) {
              if (null != o2) {
                if (o2[s2] === e3 && 1 !== t2[e3]) throw new Error(`Can't squeeze axis ${e3} since its dim '${t2[e3]}' is not 1`);
                (null == o2[s2] || o2[s2] > e3) && 1 === t2[e3] && (n2.push(t2[e3]), r2.push(e3)), o2[s2] <= e3 && s2++;
              }
              1 !== t2[e3] && (n2.push(t2[e3]), r2.push(e3));
            }
            return { newShape: n2, keptDims: r2 };
          }
          function a(t2, e2) {
            const n2 = e2.length;
            return t2 = null == t2 ? e2.map(((t3, e3) => e3)) : [].concat(t2), (0, i2.assert)(t2.every(((t3) => t3 >= -n2 && t3 < n2)), (() => `All values in axis param must be in range [-${n2}, ${n2}) but got axis ${t2}`)), (0, i2.assert)(t2.every(s), (() => `All values in axis param must be integers but got axis ${t2}`)), t2.map(((t3) => t3 < 0 ? n2 + t3 : t3));
          }
          function s(t2) {
            return t2 % 1 == 0;
          }
          function u(t2) {
            if (0 === t2.length) return 1;
            let e2 = t2[0];
            for (let n2 = 1; n2 < t2.length; n2++) e2 *= t2[n2];
            return e2;
          }
          function c(t2) {
            const e2 = Math.ceil(Math.sqrt(t2));
            return [e2, Math.ceil(t2 / e2)];
          }
          e.AlwaysKeepOriginalSizeStrategy = class {
            constructor(t2) {
              this.maxTextureSize = t2;
            }
            computeTextureWH(t2, e2) {
              if (0 === t2.length) return [1, 1];
              const n2 = this.maxTextureSize;
              if (e2 && void 0 !== e2.breakAxis) {
                const i4 = e2.breakAxis >= t2.length ? 1 : t2.slice(e2.breakAxis).reduce(((t3, e3) => t3 * e3)), o3 = e2.breakAxis <= 0 ? 1 : t2.slice(0, e2.breakAxis).reduce(((t3, e3) => t3 * e3));
                if (!(i4 > n2 || o3 > n2)) return [i4, o3];
                r.Logger.verbose("TextureLayout", `Given width/height preferences were unattainable: shape:${t2}, breakAxis:${e2.breakAxis}`);
              }
              const i3 = t2.reduce(((t3, e3) => t3 * e3));
              let o2 = Math.floor(Math.sqrt(i3));
              for (; o2 < n2 && o2 < i3 && i3 % o2 != 0; o2++) ;
              if (o2 >= n2 || i3 % o2 != 0) throw new Error(`The given dimensions are outside this GPU's boundaries: ${t2}`);
              return [o2, i3 / o2];
            }
          }, e.PreferLogicalStrategy = class {
            constructor(t2) {
              this.maxTextureSize = t2;
            }
            computeTextureWH(t2, e2) {
              const n2 = this.computeTexture(t2, e2);
              return e2 && e2.isPacked && (n2[0] /= 2, n2[1] /= 2), e2 && e2.reverseWH ? [n2[1], n2[0]] : n2;
            }
            computeTexture(t2, e2) {
              const n2 = e2 && e2.isPacked;
              if (0 === t2.length) return n2 ? [2, 2] : [1, 1];
              let i3 = this.maxTextureSize;
              if (e2 && void 0 !== e2.breakAxis) {
                const n3 = e2.breakAxis >= t2.length ? 1 : t2.slice(e2.breakAxis).reduce(((t3, e3) => t3 * e3)), o2 = e2.breakAxis <= 0 ? 1 : t2.slice(0, e2.breakAxis).reduce(((t3, e3) => t3 * e3));
                if (!(n3 > i3 || o2 > i3)) return [n3, o2];
                r.Logger.verbose("TextureLayout", `Given width/height preferences were unattainable: shape:${t2}, breakAxis:${e2.breakAxis}`);
              }
              let a2 = t2.slice(0);
              if (n2 && (i3 *= 2, a2 = a2.map(((t3, e3) => e3 >= a2.length - 2 ? a2[e3] % 2 == 0 ? a2[e3] : a2[e3] + 1 : a2[e3])), 1 === a2.length && (a2 = [2, a2[0]])), 2 !== a2.length) {
                const t3 = o(a2);
                a2 = t3.newShape;
              }
              const s2 = u(a2);
              return a2.length <= 1 && s2 <= i3 ? [1, s2] : 2 === a2.length && a2[0] <= i3 && a2[1] <= i3 ? a2 : 3 === a2.length && a2[0] * a2[1] <= i3 && a2[2] <= i3 ? [a2[0] * a2[1], a2[2]] : 3 === a2.length && a2[0] <= i3 && a2[1] * a2[2] <= i3 ? [a2[0], a2[1] * a2[2]] : 4 === a2.length && a2[0] * a2[1] * a2[2] <= i3 && a2[3] <= i3 ? [a2[0] * a2[1] * a2[2], a2[3]] : 4 === a2.length && a2[0] <= i3 && a2[1] * a2[2] * a2[3] <= i3 ? [a2[0], a2[1] * a2[2] * a2[3]] : n2 ? c(s2 / 4).map(((t3) => 2 * t3)) : c(s2);
            }
          }, e.squeezeShape = o, e.parseAxisParam = a, e.isInt = s, e.sizeFromShape = u, e.getRowsCols = function(t2) {
            if (0 === t2.length) throw Error("Cannot get rows and columns of an empty shape array.");
            return [t2.length > 1 ? t2[t2.length - 2] : 1, t2[t2.length - 1]];
          }, e.sizeToSquarishShape = c, e.getBatchDim = function(t2, e2 = 2) {
            return u(t2.slice(0, t2.length - e2));
          };
        }, 4057: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.createTextureLayoutFromShape = e.calculateTextureWidthAndHeight = e.createTextureLayoutFromTextureType = void 0;
          const r = n(2517), i2 = n(2039);
          e.createTextureLayoutFromTextureType = (t2, n2, r2) => {
            const o = r2 === i2.TextureType.unpacked || r2 === i2.TextureType.unpackedReversed ? 1 : 4, a = r2 === i2.TextureType.packed, s = r2 === i2.TextureType.unpackedReversed || r2 === i2.TextureType.packed, u = r2 === i2.TextureType.packedLastDimension ? n2.length - 1 : void 0, c = r2 === i2.TextureType.packedLastDimension ? n2.map(((t3, e2) => e2 === n2.length - 1 ? 4 * t3 : t3)) : void 0;
            return (0, e.createTextureLayoutFromShape)(t2, n2, o, c, { isPacked: a, reverseWH: s, breakAxis: u });
          }, e.calculateTextureWidthAndHeight = (t2, n2, r2) => {
            const i3 = (0, e.createTextureLayoutFromTextureType)(t2, n2, r2);
            return [i3.width, i3.height];
          }, e.createTextureLayoutFromShape = (t2, e2, n2 = 1, i3, o) => {
            const a = !(!o || !o.isPacked), [s, u] = t2.computeTextureWH(a && i3 || e2, o), c = e2.length;
            let l = e2.slice(0);
            if (0 === c && (l = [1]), 1 === n2) i3 = e2;
            else if (a) {
              if (4 !== n2) throw new Error("a packed texture must be 4-channel");
              i3 = e2, c > 0 && (l[c - 1] = Math.ceil(l[c - 1] / 2)), c > 1 && (l[c - 2] = Math.ceil(l[c - 2] / 2));
            } else if (!i3) throw new Error("Unpacked shape is needed when using channels > 1");
            return { width: s, height: u, channels: n2, isPacked: a, shape: l, strides: r.ShapeUtil.computeStrides(l), unpackedShape: i3, reversedWH: o && o.reverseWH };
          };
        }, 5702: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.TextureManager = void 0;
          const r = n(6231);
          e.TextureManager = class {
            constructor(t2, e2, n2, r2) {
              this.glContext = t2, this.layoutStrategy = e2, this.profiler = n2, this.config = r2, this.pendingRead = /* @__PURE__ */ new Map(), r2.reuseTextures && (this.inUseTextures = /* @__PURE__ */ new Map(), this.idleTextures = /* @__PURE__ */ new Map(), this.textureLookup = /* @__PURE__ */ new Map());
            }
            createTextureFromLayout(t2, e2, n2, i2) {
              const o = this.toEncoderType(t2), a = this.glContext.getEncoder(o, e2.channels || 1, i2);
              if (e2.isPacked && 1 === i2) throw new Error("not implemented");
              const s = e2.width, u = e2.height;
              let c, l;
              if (this.config.reuseTextures) {
                c = `${s}x${u}_${a.format}_${a.internalFormat}_${a.textureType}`, l = this.inUseTextures.get(c), l || (l = [], this.inUseTextures.set(c, l));
                const e3 = this.idleTextures.get(c);
                if (e3 && e3.length > 0) {
                  const r2 = e3.pop();
                  return l.push(r2), 1 === i2 && this.glContext.updateTexture(r2, s, u, a, this.toTextureData(t2, n2)), r2;
                }
              }
              r.Logger.verbose("TextureManager", `Creating new texture of size ${e2.width}x${e2.height}`);
              const p = this.glContext.allocateTexture(s, u, a, this.toTextureData(t2, n2));
              return this.config.reuseTextures && (l.push(p), this.textureLookup.set(p, c)), p;
            }
            readTexture(t2, e2, n2) {
              return n2 || (n2 = 1), this.profiler.event("backend", "TextureManager.readTexture", (() => {
                const r2 = t2.shape.reduce(((t3, e3) => t3 * e3)) * n2, i2 = this.glContext.readTexture(t2.texture, t2.width, t2.height, r2, this.toEncoderType(e2), n2);
                return this.toTensorData(e2, i2);
              }));
            }
            readTextureAsync(t2, e2, n2) {
              return __async(this, null, function* () {
                const r2 = t2.tensor.dataId;
                if (n2 || (n2 = 1), this.pendingRead.has(r2)) {
                  const t3 = this.pendingRead.get(r2);
                  return new Promise(((e3) => null == t3 ? void 0 : t3.push(e3)));
                }
                return this.profiler.event("backend", "TextureManager.readTextureAsync", (() => __async(this, null, function* () {
                  this.pendingRead.set(r2, []);
                  const i2 = t2.shape.reduce(((t3, e3) => t3 * e3)) * n2;
                  yield this.glContext.createAndWaitForFence();
                  const o = this.glContext.readTexture(t2.texture, t2.width, t2.height, i2, this.toEncoderType(e2), n2), a = this.toTensorData(e2, o), s = this.pendingRead.get(r2);
                  return this.pendingRead.delete(r2), null == s || s.forEach(((t3) => t3(a))), a;
                })));
              });
            }
            readUint8TextureAsFloat(t2) {
              return this.profiler.event("backend", "TextureManager.readUint8TextureAsFloat", (() => {
                const e2 = t2.shape.reduce(((t3, e3) => t3 * e3)), n2 = this.glContext.readTexture(t2.texture, t2.width, t2.height, 4 * e2, "byte", 4);
                return new Float32Array(n2.buffer, n2.byteOffset, e2);
              }));
            }
            releaseTexture(t2, e2) {
              let n2;
              if (this.config.reuseTextures && (n2 = this.textureLookup.get(t2.texture), n2)) {
                e2 && this.textureLookup.delete(n2);
                const r2 = this.inUseTextures.get(n2);
                if (r2) {
                  const e3 = r2.indexOf(t2.texture);
                  if (-1 !== e3) {
                    r2.splice(e3, 1);
                    let i2 = this.idleTextures.get(n2);
                    i2 || (i2 = [], this.idleTextures.set(n2, i2)), i2.push(t2.texture);
                  }
                }
              }
              n2 && !e2 || (r.Logger.verbose("TextureManager", `Deleting texture of size ${t2.width}x${t2.height}`), this.glContext.deleteTexture(t2.texture));
            }
            toTensorData(t2, e2) {
              switch (t2) {
                case "int16":
                  return e2 instanceof Int16Array ? e2 : Int16Array.from(e2);
                case "int32":
                  return e2 instanceof Int32Array ? e2 : Int32Array.from(e2);
                case "int8":
                  return e2 instanceof Int8Array ? e2 : Int8Array.from(e2);
                case "uint16":
                  return e2 instanceof Uint16Array ? e2 : Uint16Array.from(e2);
                case "uint32":
                  return e2 instanceof Uint32Array ? e2 : Uint32Array.from(e2);
                case "uint8":
                case "bool":
                  return e2 instanceof Uint8Array ? e2 : Uint8Array.from(e2);
                case "float32":
                  return e2 instanceof Float32Array ? e2 : Float32Array.from(e2);
                case "float64":
                  return e2 instanceof Float64Array ? e2 : Float64Array.from(e2);
                default:
                  throw new Error(`TensorData type ${t2} is not supported`);
              }
            }
            toTextureData(t2, e2) {
              if (e2) return e2 instanceof Float32Array ? e2 : new Float32Array(e2);
            }
            toEncoderType(t2) {
              return "float";
            }
            clearActiveTextures() {
              this.glContext.clearActiveTextures();
            }
          };
        }, 2039: (t, e) => {
          var n;
          Object.defineProperty(e, "__esModule", { value: true }), e.TextureType = void 0, (n = e.TextureType || (e.TextureType = {}))[n.unpacked = 0] = "unpacked", n[n.unpackedReversed = 1] = "unpackedReversed", n[n.packed = 2] = "packed", n[n.downloadUint8AsFloat = 3] = "downloadUint8AsFloat", n[n.packedLastDimension = 4] = "packedLastDimension";
        }, 9390: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.getGlChannels = e.getCoordsDataType = e.getSqueezedParams = e.squeezeInputShape = e.generateShaderFuncNameFromInputSamplerNameAtOutCoords = e.generateShaderFuncNameFromInputSamplerName = e.repeatedTry = e.getPackedShape = void 0;
          const r = n(2517);
          e.getPackedShape = function(t2) {
            const e2 = t2.length;
            return t2.slice(0, e2 - 1).concat(t2[e2 - 1] / 4);
          }, e.repeatedTry = function(t2, e2 = ((t3) => 0), n2) {
            return __async(this, null, function* () {
              return new Promise(((r2, i2) => {
                let o = 0;
                const a = () => {
                  if (t2()) return void r2();
                  o++;
                  const s = e2(o);
                  null != n2 && o >= n2 ? i2() : setTimeout(a, s);
                };
                a();
              }));
            });
          }, e.generateShaderFuncNameFromInputSamplerName = function(t2) {
            return (0, r.assert)(void 0 !== t2 && 0 !== t2.length, (() => "empty string found for sampler name")), "get" + t2.charAt(0).toUpperCase() + t2.slice(1);
          }, e.generateShaderFuncNameFromInputSamplerNameAtOutCoords = function(t2) {
            return (0, r.assert)(void 0 !== t2 && 0 !== t2.length, (() => "empty string found for sampler name")), "get" + t2.charAt(0).toUpperCase() + t2.slice(1) + "AtOutCoords";
          }, e.squeezeInputShape = function(t2, e2) {
            let n2 = JSON.parse(JSON.stringify(t2));
            return n2 = e2, n2;
          }, e.getSqueezedParams = function(t2, e2) {
            return e2.map(((e3) => t2[e3])).join(", ");
          }, e.getCoordsDataType = function(t2) {
            if (t2 <= 1) return "int";
            if (2 === t2) return "ivec2";
            if (3 === t2) return "ivec3";
            if (4 === t2) return "ivec4";
            if (5 === t2) return "ivec5";
            if (6 === t2) return "ivec6";
            throw Error(`GPU for rank ${t2} is not yet supported`);
          }, e.getGlChannels = function(t2 = 6) {
            return ["x", "y", "z", "w", "u", "v"].slice(0, t2);
          };
        }, 7305: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.createNewWebGLContext = e.createWebGLContext = void 0;
          const r = n(6231), i2 = n(1713), o = {};
          function a(t2) {
            const e2 = (function() {
              if ("undefined" == typeof document) {
                if ("undefined" == typeof OffscreenCanvas) throw new TypeError("failed to create canvas: OffscreenCanvas is not supported");
                return new OffscreenCanvas(1, 1);
              }
              const t3 = document.createElement("canvas");
              return t3.width = 1, t3.height = 1, t3;
            })();
            let n2;
            const o2 = { alpha: false, depth: false, antialias: false, stencil: false, preserveDrawingBuffer: false, premultipliedAlpha: false, failIfMajorPerformanceCaveat: false };
            if ((!t2 || "webgl2" === t2) && (n2 = e2.getContext("webgl2", o2), n2)) try {
              return new i2.WebGLContext(n2, 2);
            } catch (t3) {
              r.Logger.warning("GlContextFactory", `failed to create WebGLContext using contextId 'webgl2'. Error: ${t3}`);
            }
            if ((!t2 || "webgl" === t2) && (n2 = e2.getContext("webgl", o2) || e2.getContext("experimental-webgl", o2), n2)) try {
              return new i2.WebGLContext(n2, 1);
            } catch (t3) {
              r.Logger.warning("GlContextFactory", `failed to create WebGLContext using contextId 'webgl' or 'experimental-webgl'. Error: ${t3}`);
            }
            throw new Error("WebGL is not supported");
          }
          e.createWebGLContext = function t2(e2) {
            let n2;
            e2 && "webgl2" !== e2 || !("webgl2" in o) ? e2 && "webgl" !== e2 || !("webgl" in o) || (n2 = o.webgl) : n2 = o.webgl2, n2 = n2 || a(e2), e2 = e2 || 1 === n2.version ? "webgl" : "webgl2";
            const r2 = n2.gl;
            return o[e2] = n2, r2.isContextLost() ? (delete o[e2], t2(e2)) : (r2.disable(r2.DEPTH_TEST), r2.disable(r2.STENCIL_TEST), r2.disable(r2.BLEND), r2.disable(r2.DITHER), r2.disable(r2.POLYGON_OFFSET_FILL), r2.disable(r2.SAMPLE_COVERAGE), r2.enable(r2.SCISSOR_TEST), r2.enable(r2.CULL_FACE), r2.cullFace(r2.BACK), n2);
          }, e.createNewWebGLContext = a;
        }, 1713: function(t, e, n) {
          var r = this && this.__createBinding || (Object.create ? function(t2, e2, n2, r2) {
            void 0 === r2 && (r2 = n2);
            var i3 = Object.getOwnPropertyDescriptor(e2, n2);
            i3 && !("get" in i3 ? !e2.__esModule : i3.writable || i3.configurable) || (i3 = { enumerable: true, get: function() {
              return e2[n2];
            } }), Object.defineProperty(t2, r2, i3);
          } : function(t2, e2, n2, r2) {
            void 0 === r2 && (r2 = n2), t2[r2] = e2[n2];
          }), i2 = this && this.__setModuleDefault || (Object.create ? function(t2, e2) {
            Object.defineProperty(t2, "default", { enumerable: true, value: e2 });
          } : function(t2, e2) {
            t2.default = e2;
          }), o = this && this.__importStar || function(t2) {
            if (t2 && t2.__esModule) return t2;
            var e2 = {};
            if (null != t2) for (var n2 in t2) "default" !== n2 && Object.prototype.hasOwnProperty.call(t2, n2) && r(e2, t2, n2);
            return i2(e2, t2), e2;
          };
          Object.defineProperty(e, "__esModule", { value: true }), e.WebGLContext = e.linearSearchLastTrue = void 0;
          const a = n(1670), s = o(n(7769)), u = n(9390);
          function c(t2) {
            let e2 = 0;
            for (; e2 < t2.length && t2[e2](); ++e2) ;
            return e2 - 1;
          }
          e.linearSearchLastTrue = c, e.WebGLContext = class {
            constructor(t2, e2) {
              this.frameBufferBound = false, this.itemsToPoll = [], this.gl = t2, this.version = e2, this.getExtensions(), this.vertexbuffer = this.createVertexbuffer(), this.framebuffer = this.createFramebuffer(), this.queryVitalParameters();
            }
            allocateTexture(t2, e2, n2, r2) {
              const i3 = this.gl, o2 = i3.createTexture();
              i3.bindTexture(i3.TEXTURE_2D, o2), i3.texParameteri(i3.TEXTURE_2D, i3.TEXTURE_MIN_FILTER, i3.NEAREST), i3.texParameteri(i3.TEXTURE_2D, i3.TEXTURE_MAG_FILTER, i3.NEAREST), i3.texParameteri(i3.TEXTURE_2D, i3.TEXTURE_WRAP_S, i3.CLAMP_TO_EDGE), i3.texParameteri(i3.TEXTURE_2D, i3.TEXTURE_WRAP_T, i3.CLAMP_TO_EDGE);
              const a2 = r2 ? n2.encode(r2, t2 * e2) : null;
              return i3.texImage2D(i3.TEXTURE_2D, 0, n2.internalFormat, t2, e2, 0, n2.format, n2.textureType, a2), this.checkError(), o2;
            }
            updateTexture(t2, e2, n2, r2, i3) {
              const o2 = this.gl;
              o2.bindTexture(o2.TEXTURE_2D, t2);
              const a2 = r2.encode(i3, e2 * n2);
              o2.texSubImage2D(o2.TEXTURE_2D, 0, 0, 0, e2, n2, r2.format, r2.textureType, a2), this.checkError();
            }
            attachFramebuffer(t2, e2, n2) {
              const r2 = this.gl;
              r2.bindTexture(r2.TEXTURE_2D, t2), r2.bindFramebuffer(r2.FRAMEBUFFER, this.framebuffer), r2.framebufferTexture2D(r2.FRAMEBUFFER, r2.COLOR_ATTACHMENT0, r2.TEXTURE_2D, t2, 0), this.checkError(), r2.viewport(0, 0, e2, n2), r2.scissor(0, 0, e2, n2);
            }
            readTexture(t2, e2, n2, r2, i3, o2) {
              const a2 = this.gl;
              o2 || (o2 = 1), this.frameBufferBound || this.attachFramebuffer(t2, e2, n2);
              const s2 = this.getEncoder(i3, o2), u2 = s2.allocate(e2 * n2);
              return a2.bindTexture(a2.TEXTURE_2D, t2), a2.framebufferTexture2D(a2.FRAMEBUFFER, a2.COLOR_ATTACHMENT0, a2.TEXTURE_2D, t2, 0), a2.readPixels(0, 0, e2, n2, a2.RGBA, s2.textureType, u2), this.checkError(), s2.decode(u2, r2);
            }
            isFramebufferReady() {
              return true;
            }
            getActiveTexture() {
              const t2 = this.gl;
              return "TEXTURE" + (t2.getParameter(this.gl.ACTIVE_TEXTURE) - t2.TEXTURE0);
            }
            getTextureBinding() {
              return this.gl.getParameter(this.gl.TEXTURE_BINDING_2D);
            }
            getFramebufferBinding() {
              return this.gl.getParameter(this.gl.FRAMEBUFFER_BINDING);
            }
            setVertexAttributes(t2, e2) {
              const n2 = this.gl;
              n2.vertexAttribPointer(t2, 3, n2.FLOAT, false, 20, 0), n2.enableVertexAttribArray(t2), -1 !== e2 && (n2.vertexAttribPointer(e2, 2, n2.FLOAT, false, 20, 12), n2.enableVertexAttribArray(e2)), this.checkError();
            }
            createProgram(t2, e2) {
              const n2 = this.gl, r2 = n2.createProgram();
              return n2.attachShader(r2, t2), n2.attachShader(r2, e2), n2.linkProgram(r2), r2;
            }
            compileShader(t2, e2) {
              const n2 = this.gl, r2 = n2.createShader(e2);
              if (!r2) throw new Error(`createShader() returned null with type ${e2}`);
              if (n2.shaderSource(r2, t2), n2.compileShader(r2), false === n2.getShaderParameter(r2, n2.COMPILE_STATUS)) throw new Error(`Failed to compile shader: ${n2.getShaderInfoLog(r2)}
Shader source:
${t2}`);
              return r2;
            }
            deleteShader(t2) {
              this.gl.deleteShader(t2);
            }
            bindTextureToUniform(t2, e2, n2) {
              const r2 = this.gl;
              r2.activeTexture(r2.TEXTURE0 + e2), this.checkError(), r2.bindTexture(r2.TEXTURE_2D, t2), this.checkError(), r2.uniform1i(n2, e2), this.checkError();
            }
            draw() {
              this.gl.drawArrays(this.gl.TRIANGLE_STRIP, 0, 4), this.checkError();
            }
            checkError() {
              if (a.env.debug) {
                const t2 = this.gl, e2 = t2.getError();
                let n2 = "";
                switch (e2) {
                  case t2.NO_ERROR:
                    return;
                  case t2.INVALID_ENUM:
                    n2 = "INVALID_ENUM";
                    break;
                  case t2.INVALID_VALUE:
                    n2 = "INVALID_VALUE";
                    break;
                  case t2.INVALID_OPERATION:
                    n2 = "INVALID_OPERATION";
                    break;
                  case t2.INVALID_FRAMEBUFFER_OPERATION:
                    n2 = "INVALID_FRAMEBUFFER_OPERATION";
                    break;
                  case t2.OUT_OF_MEMORY:
                    n2 = "OUT_OF_MEMORY";
                    break;
                  case t2.CONTEXT_LOST_WEBGL:
                    n2 = "CONTEXT_LOST_WEBGL";
                    break;
                  default:
                    n2 = `Unknown WebGL Error: ${e2.toString(16)}`;
                }
                throw new Error(n2);
              }
            }
            deleteTexture(t2) {
              this.gl.deleteTexture(t2);
            }
            deleteProgram(t2) {
              this.gl.deleteProgram(t2);
            }
            getEncoder(t2, e2, n2 = 0) {
              if (2 === this.version) return new s.RedFloat32DataEncoder(this.gl, e2);
              switch (t2) {
                case "float":
                  return 1 === n2 || this.isRenderFloat32Supported ? new s.RGBAFloatDataEncoder(this.gl, e2) : new s.RGBAFloatDataEncoder(this.gl, e2, this.textureHalfFloatExtension.HALF_FLOAT_OES);
                case "int":
                  throw new Error("not implemented");
                case "byte":
                  return new s.Uint8DataEncoder(this.gl, e2);
                default:
                  throw new Error(`Invalid dataType: ${t2}`);
              }
            }
            clearActiveTextures() {
              const t2 = this.gl;
              for (let e2 = 0; e2 < this.maxTextureImageUnits; ++e2) t2.activeTexture(t2.TEXTURE0 + e2), t2.bindTexture(t2.TEXTURE_2D, null);
            }
            dispose() {
              if (this.disposed) return;
              const t2 = this.gl;
              t2.bindFramebuffer(t2.FRAMEBUFFER, null), t2.deleteFramebuffer(this.framebuffer), t2.bindBuffer(t2.ARRAY_BUFFER, null), t2.deleteBuffer(this.vertexbuffer), t2.bindBuffer(t2.ELEMENT_ARRAY_BUFFER, null), t2.finish(), this.disposed = true;
            }
            createDefaultGeometry() {
              return new Float32Array([-1, 1, 0, 0, 1, -1, -1, 0, 0, 0, 1, 1, 0, 1, 1, 1, -1, 0, 1, 0]);
            }
            createVertexbuffer() {
              const t2 = this.gl, e2 = t2.createBuffer();
              if (!e2) throw new Error("createBuffer() returned null");
              const n2 = this.createDefaultGeometry();
              return t2.bindBuffer(t2.ARRAY_BUFFER, e2), t2.bufferData(t2.ARRAY_BUFFER, n2, t2.STATIC_DRAW), this.checkError(), e2;
            }
            createFramebuffer() {
              const t2 = this.gl.createFramebuffer();
              if (!t2) throw new Error("createFramebuffer returned null");
              return t2;
            }
            queryVitalParameters() {
              const t2 = this.gl;
              if (this.isFloatTextureAttachableToFrameBuffer = this.checkFloatTextureAttachableToFrameBuffer(), this.isRenderFloat32Supported = this.checkRenderFloat32(), this.isFloat32DownloadSupported = this.checkFloat32Download(), 1 === this.version && !this.textureHalfFloatExtension && !this.isRenderFloat32Supported) throw new Error("both float32 and float16 TextureType are not supported");
              this.isBlendSupported = !this.isRenderFloat32Supported || this.checkFloat32Blend(), this.maxTextureSize = t2.getParameter(t2.MAX_TEXTURE_SIZE), this.maxTextureImageUnits = t2.getParameter(t2.MAX_TEXTURE_IMAGE_UNITS), this.version;
            }
            getExtensions() {
              2 === this.version ? (this.colorBufferFloatExtension = this.gl.getExtension("EXT_color_buffer_float"), this.disjointTimerQueryWebgl2Extension = this.gl.getExtension("EXT_disjoint_timer_query_webgl2")) : (this.textureFloatExtension = this.gl.getExtension("OES_texture_float"), this.textureHalfFloatExtension = this.gl.getExtension("OES_texture_half_float"));
            }
            checkFloatTextureAttachableToFrameBuffer() {
              const t2 = this.gl, e2 = t2.createTexture();
              t2.bindTexture(t2.TEXTURE_2D, e2);
              const n2 = 2 === this.version ? t2.RGBA32F : t2.RGBA;
              t2.texImage2D(t2.TEXTURE_2D, 0, n2, 1, 1, 0, t2.RGBA, t2.FLOAT, null);
              const r2 = t2.createFramebuffer();
              t2.bindFramebuffer(t2.FRAMEBUFFER, r2), t2.framebufferTexture2D(t2.FRAMEBUFFER, t2.COLOR_ATTACHMENT0, t2.TEXTURE_2D, e2, 0);
              const i3 = t2.checkFramebufferStatus(t2.FRAMEBUFFER) === t2.FRAMEBUFFER_COMPLETE;
              return t2.bindTexture(t2.TEXTURE_2D, null), t2.bindFramebuffer(t2.FRAMEBUFFER, null), t2.deleteTexture(e2), t2.deleteFramebuffer(r2), i3;
            }
            checkRenderFloat32() {
              if (2 === this.version) {
                if (!this.colorBufferFloatExtension) return false;
              } else if (!this.textureFloatExtension) return false;
              return this.isFloatTextureAttachableToFrameBuffer;
            }
            checkFloat32Download() {
              if (2 === this.version) {
                if (!this.colorBufferFloatExtension) return false;
              } else {
                if (!this.textureFloatExtension) return false;
                if (!this.gl.getExtension("WEBGL_color_buffer_float")) return false;
              }
              return this.isFloatTextureAttachableToFrameBuffer;
            }
            checkFloat32Blend() {
              const t2 = this.gl;
              let e2, n2, r2, i3, o2;
              try {
                e2 = t2.createTexture(), n2 = t2.createFramebuffer(), t2.bindTexture(t2.TEXTURE_2D, e2);
                const a2 = 2 === this.version ? t2.RGBA32F : t2.RGBA;
                return t2.texImage2D(t2.TEXTURE_2D, 0, a2, 1, 1, 0, t2.RGBA, t2.FLOAT, null), t2.bindFramebuffer(t2.FRAMEBUFFER, n2), t2.framebufferTexture2D(t2.FRAMEBUFFER, t2.COLOR_ATTACHMENT0, t2.TEXTURE_2D, e2, 0), t2.enable(t2.BLEND), r2 = t2.createShader(t2.VERTEX_SHADER), !!r2 && (t2.shaderSource(r2, "void main(){}"), t2.compileShader(r2), i3 = t2.createShader(t2.FRAGMENT_SHADER), !!i3 && (t2.shaderSource(i3, "precision highp float;void main(){gl_FragColor=vec4(0.5);}"), t2.compileShader(i3), o2 = t2.createProgram(), !!o2 && (t2.attachShader(o2, r2), t2.attachShader(o2, i3), t2.linkProgram(o2), t2.useProgram(o2), t2.drawArrays(t2.POINTS, 0, 1), t2.getError() === t2.NO_ERROR)));
              } finally {
                t2.disable(t2.BLEND), o2 && t2.deleteProgram(o2), r2 && t2.deleteShader(r2), i3 && t2.deleteShader(i3), n2 && (t2.bindFramebuffer(t2.FRAMEBUFFER, null), t2.deleteFramebuffer(n2)), e2 && (t2.bindTexture(t2.TEXTURE_2D, null), t2.deleteTexture(e2));
              }
            }
            beginTimer() {
              if (2 === this.version && this.disjointTimerQueryWebgl2Extension) {
                const t2 = this.gl, e2 = this.disjointTimerQueryWebgl2Extension, n2 = t2.createQuery();
                return t2.beginQuery(e2.TIME_ELAPSED_EXT, n2), n2;
              }
              throw new Error("WebGL1 profiling currently not supported.");
            }
            endTimer() {
              if (2 !== this.version || !this.disjointTimerQueryWebgl2Extension) throw new Error("WebGL1 profiling currently not supported");
              {
                const t2 = this.gl, e2 = this.disjointTimerQueryWebgl2Extension;
                t2.endQuery(e2.TIME_ELAPSED_EXT);
              }
            }
            isTimerResultAvailable(t2) {
              let e2 = false, n2 = false;
              if (2 !== this.version || !this.disjointTimerQueryWebgl2Extension) throw new Error("WebGL1 profiling currently not supported");
              {
                const r2 = this.gl, i3 = this.disjointTimerQueryWebgl2Extension;
                e2 = r2.getQueryParameter(t2, r2.QUERY_RESULT_AVAILABLE), n2 = r2.getParameter(i3.GPU_DISJOINT_EXT);
              }
              return e2 && !n2;
            }
            getTimerResult(t2) {
              let e2 = 0;
              if (2 !== this.version) throw new Error("WebGL1 profiling currently not supported");
              {
                const n2 = this.gl;
                e2 = n2.getQueryParameter(t2, n2.QUERY_RESULT), n2.deleteQuery(t2);
              }
              return e2 / 1e6;
            }
            waitForQueryAndGetTime(t2) {
              return __async(this, null, function* () {
                return yield (0, u.repeatedTry)((() => this.isTimerResultAvailable(t2))), this.getTimerResult(t2);
              });
            }
            createAndWaitForFence() {
              return __async(this, null, function* () {
                const t2 = this.createFence(this.gl);
                return this.pollFence(t2);
              });
            }
            createFence(t2) {
              let e2;
              const n2 = t2, r2 = n2.fenceSync(n2.SYNC_GPU_COMMANDS_COMPLETE, 0);
              return t2.flush(), e2 = null === r2 ? () => true : () => {
                const t3 = n2.clientWaitSync(r2, 0, 0);
                return t3 === n2.ALREADY_SIGNALED || t3 === n2.CONDITION_SATISFIED;
              }, { query: r2, isFencePassed: e2 };
            }
            pollFence(t2) {
              return __async(this, null, function* () {
                return new Promise(((e2) => {
                  this.addItemToPoll((() => t2.isFencePassed()), (() => e2()));
                }));
              });
            }
            pollItems() {
              const t2 = c(this.itemsToPoll.map(((t3) => t3.isDoneFn)));
              for (let e2 = 0; e2 <= t2; ++e2) {
                const { resolveFn: t3 } = this.itemsToPoll[e2];
                t3();
              }
              this.itemsToPoll = this.itemsToPoll.slice(t2 + 1);
            }
            addItemToPoll(t2, e2) {
              return __async(this, null, function* () {
                this.itemsToPoll.push({ isDoneFn: t2, resolveFn: e2 }), this.itemsToPoll.length > 1 || (yield (0, u.repeatedTry)((() => (this.pollItems(), 0 === this.itemsToPoll.length))));
              });
            }
          };
        }, 1036: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.ExecutionPlan = void 0;
          const r = n(6231);
          class i2 {
            constructor(t2, e2) {
              this.op = t2, this.node = e2;
            }
          }
          e.ExecutionPlan = class {
            constructor(t2, e2, n2) {
              this.graph = t2, this.profiler = n2, this.initialize(e2);
            }
            initialize(t2) {
              this.profiler.event("session", "ExecutionPlan.initialize", (() => {
                const e2 = this.graph.getNodes();
                if (e2.length !== t2.length) throw new Error("The size of nodes and OPs do not match.");
                this._ops = t2.map(((t3, n2) => new i2(t3, e2[n2]))), this.reset(), this._starter = [], this._ops.forEach(((t3, e3) => {
                  let n2 = true;
                  for (const e4 of t3.node.inputs) if (!this._values[e4] && -1 === this.graph.getInputIndices().indexOf(e4)) {
                    n2 = false;
                    break;
                  }
                  n2 && this._starter.push(e3);
                }));
              }));
            }
            reset() {
              this._values = this.graph.getValues().map(((t2) => t2.tensor));
            }
            execute(t2, e2) {
              return __async(this, null, function* () {
                return this.profiler.event("session", "ExecutionPlan.execute", (() => __async(this, null, function* () {
                  this.reset();
                  const n2 = t2.createInferenceHandler(), i3 = this.graph.getInputIndices();
                  if (e2.length !== i3.length) throw new Error(`number of input tensors don't match the number of inputs to the model: actual: ${e2.length} expected: ${i3.length}`);
                  e2.forEach(((t3, e3) => {
                    const n3 = i3[e3];
                    this._values[n3] = t3;
                  }));
                  const o = this._starter.slice(0), a = this.graph.getValues(), s = this.graph.getNodes();
                  let u = 0;
                  for (; u < o.length; ) {
                    const t3 = o[u++], e3 = this._ops[t3], i4 = e3.node.inputs.map(((t4) => this._values[t4]));
                    if (-1 !== i4.indexOf(void 0)) throw new Error(`unresolved input detected: op: ${e3.node}`);
                    const c2 = i4;
                    r.Logger.verbose("ExecPlan", `Runing op:${e3.node.name} (${c2.map(((t4, n3) => `'${e3.node.inputs[n3]}': ${t4.type}[${t4.dims.join(",")}]`)).join(", ")})`);
                    const l = yield this.profiler.event("node", e3.node.name, (() => __async(this, null, function* () {
                      return e3.op.impl(n2, c2, e3.op.context);
                    })));
                    if (l.length !== e3.node.outputs.length) throw new Error("the size of output does not match model definition.");
                    l.forEach(((t4, n3) => {
                      const r2 = e3.node.outputs[n3];
                      if (this._values[r2]) throw new Error(`output [${r2}] already has value: op:${e3.node.name}`);
                      this._values[r2] = t4;
                    }));
                    const p = /* @__PURE__ */ new Set();
                    l.forEach(((t4, n3) => {
                      const r2 = e3.node.outputs[n3];
                      for (const t5 of a[r2].to) {
                        const e4 = s[t5];
                        let n4 = true;
                        for (const t6 of e4.inputs) if (!this._values[t6]) {
                          n4 = false;
                          break;
                        }
                        n4 && p.add(t5);
                      }
                    })), o.push(...p);
                  }
                  const c = [];
                  for (let t3 = 0; t3 < this.graph.getOutputIndices().length; t3++) {
                    const e3 = this.graph.getOutputIndices()[t3], n3 = this._values[e3];
                    if (void 0 === n3) throw new Error(`required output [${e3}] does not have value`);
                    0 === e3 ? yield n3.getData() : n3.data, c.push(n3);
                  }
                  return r.Logger.verbose("ExecPlan", "disposing of inferenceHandler"), n2.dispose(), c;
                })));
              });
            }
          };
        }, 7070: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.Graph = void 0;
          const r = n(1446), i2 = n(7778), o = n(9395), a = n(9162), s = n(2517);
          var u = o.onnxruntime.experimental.fbs;
          e.Graph = { from: (t2, e2) => new p(t2, e2) };
          class c {
            constructor(t2) {
              this._from = void 0, this._to = [], this.tensor = void 0, this.type = void 0, t2 && (this.type = s.ProtoUtil.tensorValueTypeFromProto(t2.type.tensorType));
            }
            get from() {
              return this._from;
            }
            get to() {
              return this._to;
            }
          }
          class l {
            constructor(t2, e2) {
              t2 instanceof r.onnx.NodeProto ? (this.name = t2.name, this.opType = t2.opType, this.attributes = new i2.Attribute(t2.attribute)) : t2 instanceof u.Node && (this.name = null != e2 ? e2 : t2.name(), this.opType = t2.opType(), this.attributes = new i2.Attribute(s.ProtoUtil.tensorAttributesFromORTFormat(t2))), this.inputs = [], this.outputs = [], this.executeNode = true;
            }
          }
          class p {
            constructor(t2, e2) {
              if (!t2) throw new TypeError("graph is empty");
              this.buildGraph(t2), this.transformGraph(e2), 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(t2) {
              if (t2 instanceof r.onnx.GraphProto) this.buildGraphFromOnnxFormat(t2);
              else {
                if (!(t2 instanceof u.Graph)) throw new TypeError("Graph type is not supported.");
                this.buildGraphFromOrtFormat(t2);
              }
            }
            buildGraphFromOnnxFormat(t2) {
              const e2 = /* @__PURE__ */ new Map();
              this._allData = [], this._allInputIndices = [], this._allInputNames = [], this._allOutputIndices = [], this._allOutputNames = [], this._nodes = [];
              const n2 = /* @__PURE__ */ new Map();
              if (!t2.input) throw new Error("missing information in graph: input");
              const r2 = [];
              for (const n3 of t2.input) {
                if (e2.has(n3.name)) throw new Error(`duplicated input name: ${n3.name}`);
                const t3 = this._allData.push(new c(n3)) - 1;
                e2.set(n3.name, t3), r2.push(n3.name);
              }
              if (!t2.initializer) throw new Error("missing information in graph: initializer");
              for (const n3 of t2.initializer) {
                let t3 = e2.get(n3.name);
                if (void 0 === t3) {
                  const r3 = new c();
                  r3.type = { shape: { dims: s.ProtoUtil.tensorDimsFromProto(n3.dims) }, tensorType: s.ProtoUtil.tensorDataTypeFromProto(n3.dataType) }, t3 = this._allData.push(r3) - 1, e2.set(n3.name, t3);
                }
                this._allData[t3]._from = -1, this._allData[t3].tensor = a.Tensor.fromProto(n3);
              }
              for (let t3 = 0; t3 < this._allData.length; t3++) this._allData[t3].tensor || (this._allInputIndices.push(t3), this._allInputNames.push(r2[t3]));
              if (!t2.output) throw new Error("missing information in graph: output");
              for (const n3 of t2.output) {
                if (e2.has(n3.name)) throw new Error(`duplicated output name: ${n3.name}`);
                const t3 = this._allData.push(new c(n3)) - 1;
                e2.set(n3.name, t3), this._allOutputIndices.push(t3), this._allOutputNames.push(n3.name);
              }
              if (!t2.node) throw new Error("missing information in graph: node");
              for (const e3 of t2.node) {
                if (!e3.name) for (let t4 = 0; ; t4++) {
                  const r3 = `unnamed_${e3.opType}_${t4}`;
                  if (!n2.has(r3)) {
                    e3.name = r3;
                    break;
                  }
                }
                if (n2.has(e3.name)) throw new Error(`duplicated node name: ${e3.name}`);
                const t3 = this._nodes.push(new l(e3)) - 1;
                n2.set(e3.name, t3);
              }
              for (let n3 = 0; n3 < this._nodes.length; n3++) {
                const r3 = this._nodes[n3], i3 = t2.node[n3];
                if (!i3.output) throw new Error(`missing output for node: ${i3.name}`);
                for (const t3 of i3.output) {
                  let o2 = e2.get(t3);
                  if (void 0 === o2 && (o2 = this._allData.push(new c()) - 1, e2.set(t3, o2)), r3.outputs.push(o2), void 0 !== this._allData[o2]._from) throw new Error(`multiple nodes output to one data value: ${o2}`);
                  if (this._allData[o2]._from = n3, "Constant" === i3.opType) {
                    if (!i3.attribute || 1 !== i3.attribute.length || !i3.attribute[0].t) throw new Error("missing attributes or missing tensor value in attributes for this Constant operator");
                    if (!i3.output || 1 !== i3.output.length) throw new Error("missing output or incorrect number of outputs for this Constant operator");
                    r3.outputs.pop(), r3.executeNode = false, this._allData[o2]._from = -1, this._allData[o2].tensor = a.Tensor.fromProto(i3.attribute[0].t);
                  }
                }
              }
              for (let n3 = 0; n3 < this._nodes.length; n3++) {
                const r3 = this._nodes[n3], i3 = t2.node[n3];
                if (!i3.input) throw new Error(`missing input for node: ${i3.name}`);
                for (const t3 of i3.input) {
                  const o2 = e2.get(t3);
                  if (void 0 === o2) {
                    if ("" === t3 && 3 === i3.input.length && "Resize" === i3.opType) continue;
                    throw new Error(`unrecognized input '${t3}' for node: ${i3.name}`);
                  }
                  r3.inputs.push(o2), this._allData[o2]._to.push(n3);
                }
              }
              return true;
            }
            buildGraphFromOrtFormat(t2) {
              var e2, n2, r2;
              const i3 = /* @__PURE__ */ new Map();
              this._allData = [], this._allInputIndices = [], this._allInputNames = [], this._allOutputIndices = [], this._allOutputNames = [], this._nodes = [];
              const o2 = /* @__PURE__ */ new Map(), p2 = [];
              for (let o3 = 0; o3 < t2.inputsLength(); o3++) {
                const a2 = t2.inputs(o3);
                if (i3.has(a2)) throw new Error(`duplicated input name: ${a2}`);
                for (let o4 = 0; o4 < t2.nodeArgsLength(); o4++) if ((null === (e2 = t2.nodeArgs(o4)) || void 0 === e2 ? void 0 : e2.name()) === a2) {
                  const e3 = new c();
                  if ((null === (r2 = null === (n2 = t2.nodeArgs(o4)) || void 0 === n2 ? void 0 : n2.type()) || void 0 === r2 ? void 0 : r2.valueType()) !== u.TypeInfoValue.tensor_type) throw new Error("Unexpected value type for the nodeArg.");
                  const l2 = t2.nodeArgs(o4).type().value(new u.TensorTypeAndShape()), f = s.ProtoUtil.tensorDataTypeFromProto(l2.elemType()), d = l2.shape(), h = [];
                  for (let t3 = 0; t3 < d.dimLength(); t3++) h.push(s.LongUtil.longToNumber(d.dim(t3).value().dimValue()));
                  e3.type = { shape: { dims: h }, tensorType: f };
                  const g = this._allData.push(e3) - 1;
                  i3.set(a2, g), p2.push(a2);
                }
              }
              for (let e3 = 0; e3 < t2.initializersLength(); e3++) {
                const n3 = t2.initializers(e3);
                let r3 = i3.get(n3.name());
                if (void 0 === r3) {
                  const t3 = new c(), e4 = s.ProtoUtil.tensorDimsFromORTFormat(n3), o3 = s.ProtoUtil.tensorDataTypeFromProto(n3.dataType());
                  t3.type = { shape: { dims: e4 }, tensorType: o3 }, r3 = this._allData.push(t3) - 1, i3.set(n3.name(), r3);
                }
                this._allData[r3]._from = -1, this._allData[r3].tensor = a.Tensor.fromOrtTensor(n3);
              }
              for (let t3 = 0; t3 < this._allData.length; t3++) this._allData[t3].tensor || (this._allInputIndices.push(t3), this._allInputNames.push(p2[t3]));
              for (let e3 = 0; e3 < t2.outputsLength(); e3++) {
                const n3 = t2.outputs(e3);
                if (i3.has(n3)) throw new Error(`duplicated output name: ${n3}`);
                const r3 = this._allData.push(new c()) - 1;
                i3.set(n3, r3), this._allOutputIndices.push(r3), this._allOutputNames.push(n3);
              }
              if (!t2.nodes) throw new Error("missing information in graph: node");
              for (let e3 = 0; e3 < t2.nodesLength(); e3++) {
                const n3 = t2.nodes(e3);
                let r3 = n3.name();
                if (!r3) for (let t3 = 0; r3 = `unnamed_${n3.opType()}_${t3}`, o2.has(r3); t3++) ;
                if (o2.has(r3)) throw new Error(`duplicated node name: ${r3}`);
                const i4 = this._nodes.push(new l(n3, r3)) - 1;
                o2.set(r3, i4);
              }
              for (let e3 = 0; e3 < this._nodes.length; e3++) {
                const n3 = this._nodes[e3], r3 = t2.nodes(e3);
                if (null == r3) throw new Error(`No node exists at index ${e3}`);
                if (0 === (null == r3 ? void 0 : r3.outputsLength())) throw new Error(`missing output for node: ${r3.name}`);
                for (let t3 = 0; t3 < (null == r3 ? void 0 : r3.outputsLength()); t3++) {
                  const o3 = null == r3 ? void 0 : r3.outputs(t3);
                  let s2 = i3.get(o3);
                  if (void 0 === s2 && (s2 = this._allData.push(new c()) - 1, i3.set(o3, s2)), n3.outputs.push(s2), void 0 !== this._allData[s2]._from) throw new Error(`multiple nodes output to one data value: ${s2}`);
                  if (this._allData[s2]._from = e3, "Constant" === r3.opType()) {
                    if (1 !== r3.attributesLength() || !r3.attributes(0).t()) throw new Error("missing attributes or missing tensor value in attributes for this Constant operator");
                    if (1 !== r3.outputsLength()) throw new Error("missing output or incorrect number of outputs for this Constant operator");
                    n3.outputs.pop(), n3.executeNode = false, this._allData[s2]._from = -1, this._allData[s2].tensor = a.Tensor.fromOrtTensor(r3.attributes(0).t());
                  }
                }
              }
              for (let e3 = 0; e3 < this._nodes.length; e3++) {
                const n3 = this._nodes[e3], r3 = t2.nodes(e3);
                if (0 === r3.inputsLength()) throw new Error(`missing input for node: ${r3.name}`);
                for (let t3 = 0; t3 < r3.inputsLength(); t3++) {
                  const o3 = r3.inputs(t3), a2 = i3.get(o3);
                  if (void 0 === a2) throw new Error(`unrecognized input '${o3}' for node: ${r3.name()}`);
                  n3.inputs.push(a2), this._allData[a2]._to.push(e3);
                }
              }
            }
            checkIsAcyclic() {
              const t2 = /* @__PURE__ */ new Set();
              this._allInputIndices.forEach(((e3) => {
                this._allData[e3]._to.forEach(((e4) => {
                  t2.add(e4);
                }));
              }));
              const e2 = Array.from(t2), n2 = new Array(this._nodes.length).fill("white");
              for (; e2.length > 0; ) {
                const t3 = e2.pop();
                "gray" === n2[t3] ? n2[t3] = "black" : (e2.push(t3), n2[t3] = "gray", this._nodes[t3].outputs.forEach(((r2) => {
                  const i3 = this._allData[r2];
                  if (void 0 !== i3.tensor) throw new Error("node outputs should not be initialized");
                  if (i3._from !== t3) throw new Error("from property of the Value object doesn't match index of Node being processed");
                  i3._to.forEach(((t4) => {
                    if ("gray" === n2[t4]) throw new Error("model graph is cyclic");
                    "white" === n2[t4] && e2.push(t4);
                  }));
                })));
              }
            }
            transformGraph(t2) {
              this.removeAllIdentityNodes(), this.removeAllDropoutNodes(), this.fuseConvActivationNodes(), t2 && t2.transformGraph(this), this.finalizeGraph();
            }
            finalizeGraph() {
              let t2 = 0;
              for (let e2 = 0; e2 < this._nodes.length; e2++) this._nodes[e2].executeNode ? t2 > 0 && (this._nodes[e2].inputs.forEach(((n2) => {
                const r2 = this._allData[n2]._to.indexOf(e2 + t2);
                -1 !== r2 && (this._allData[n2]._to[r2] = e2);
              })), this._nodes[e2].outputs.forEach(((n2) => {
                this._allData[n2]._from && this._allData[n2]._from === e2 + t2 && (this._allData[n2]._from = e2);
              }))) : (t2++, this._nodes[e2].outputs.forEach(((t3) => {
                this._allData[t3]._from = -2;
              })), this._nodes.splice(e2, 1), e2--);
              t2 = 0;
              for (let e2 = 0; e2 < this._allData.length; e2++) if (-2 !== this._allData[e2].from || -1 !== this._allOutputIndices.indexOf(e2 + t2)) {
                if (t2 > 0) {
                  let n2 = -1;
                  void 0 !== this._allData[e2].from && -1 !== this._allData[e2].from ? (n2 = this._nodes[this._allData[e2].from].outputs.indexOf(e2 + t2), -1 !== n2 && (this._nodes[this._allData[e2].from].outputs[n2] = e2)) : (n2 = this._allInputIndices.indexOf(e2 + t2), -1 !== n2 && (this._allInputIndices[n2] = e2)), this._allData[e2].to.forEach(((r2) => {
                    n2 = this._nodes[r2].inputs.indexOf(e2 + t2), -1 !== n2 && (this._nodes[r2].inputs[n2] = e2);
                  })), 0 === this._allData[e2].to.length && (n2 = this._allOutputIndices.indexOf(e2 + t2), -1 !== n2 && (this._allOutputIndices[n2] = e2));
                }
              } else t2++, this._allData.splice(e2, 1), e2--;
            }
            deleteNode(t2) {
              const e2 = this._nodes[t2];
              if (e2.outputs.length > 1) {
                for (let t3 = 1; t3 < e2.outputs.length; t3++) if (this._allData[e2.outputs[t3]].to.length > 0) throw new Error("Node deletion with more than one output connected to other nodes is not supported. ");
              }
              e2.executeNode = false;
              const n2 = e2.inputs[0], r2 = e2.outputs[0], i3 = this._allData[r2].to, o2 = this._allData[n2].to.indexOf(t2);
              if (-1 === o2) throw new Error("The Value object doesn't have the current Node in it's 'to' property ");
              this._allData[n2].to.splice(o2, 1), this._allData[r2]._to = [];
              const a2 = this._allOutputIndices.indexOf(r2);
              if (-1 !== a2 && (this._allOutputIndices[a2] = n2), i3 && i3.length > 0) for (const t3 of i3) {
                const e3 = this._nodes[t3].inputs.indexOf(r2);
                if (-1 === e3) throw new Error("The Node object doesn't have the output Value in it's 'inputs' property ");
                this._nodes[t3].inputs[e3] = n2, this._allData[n2].to.push(t3);
              }
            }
            removeAllDropoutNodes() {
              let t2 = 0;
              for (const e2 of this._nodes) {
                if ("Dropout" === e2.opType) {
                  if (1 !== e2.inputs.length) throw new Error("Dropout nodes should only contain one input. ");
                  if (1 !== e2.outputs.length && 2 !== e2.outputs.length) throw new Error("Dropout nodes should contain either 1 or 2 output(s)");
                  if (2 === e2.outputs.length && 0 !== this._allData[e2.outputs[1]]._to.length) throw new Error("Dropout nodes's second output should not be referenced by other nodes");
                  this.deleteNode(t2);
                }
                t2++;
              }
            }
            removeAllIdentityNodes() {
              let t2 = 0;
              for (const e2 of this._nodes) "Identity" === e2.opType && this.deleteNode(t2), t2++;
            }
            isActivation(t2) {
              switch (t2.opType) {
                case "Relu":
                case "Sigmoid":
                case "Clip":
                  return true;
                default:
                  return false;
              }
            }
            fuseConvActivationNodes() {
              for (const t2 of this._nodes) if ("Conv" === t2.opType) {
                const e2 = this._allData[t2.outputs[0]]._to;
                if (1 === e2.length && this.isActivation(this._nodes[e2[0]])) {
                  const n2 = this._nodes[e2[0]];
                  if ("Clip" === n2.opType) if (1 === n2.inputs.length) try {
                    t2.attributes.set("activation_params", "floats", [n2.attributes.getFloat("min"), n2.attributes.getFloat("max")]);
                  } catch (e3) {
                    t2.attributes.set("activation_params", "floats", [s.MIN_CLIP, s.MAX_CLIP]);
                  }
                  else {
                    if (!(n2.inputs.length >= 3 && void 0 !== this._allData[n2.inputs[1]].tensor && void 0 !== this._allData[n2.inputs[2]].tensor)) continue;
                    t2.attributes.set("activation_params", "floats", [this._allData[n2.inputs[1]].tensor.floatData[0], this._allData[n2.inputs[2]].tensor.floatData[0]]);
                  }
                  t2.attributes.set("activation", "string", n2.opType), this.deleteNode(e2[0]);
                }
              }
            }
          }
        }, 6231: (t, e) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.now = e.Profiler = e.Logger = void 0;
          const n = { verbose: 1e3, info: 2e3, warning: 4e3, error: 5e3, fatal: 6e3 }, r = { none: new class {
            log(t2, e2, n2) {
            }
          }(), console: new class {
            log(t2, e2, n2) {
              console.log(`${this.color(t2)} ${n2 ? "\x1B[35m" + n2 + "\x1B[0m " : ""}${e2}`);
            }
            color(t2) {
              switch (t2) {
                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: ${t2}`);
              }
            }
          }() }, i2 = { provider: "console", minimalSeverity: "warning", logDateTime: true, logSourceLocation: false };
          let o = { "": i2 };
          function a(t2, e2, n2, r2) {
            if (void 0 === e2) return i3 = t2, { verbose: a.verbose.bind(null, i3), info: a.info.bind(null, i3), warning: a.warning.bind(null, i3), error: a.error.bind(null, i3), fatal: a.fatal.bind(null, i3) };
            if (void 0 === n2) s(t2, e2);
            else if ("number" == typeof n2 && void 0 === r2) s(t2, e2);
            else if ("string" == typeof n2 && void 0 === r2) s(t2, n2, 0, e2);
            else {
              if ("string" != typeof n2 || "number" != typeof r2) throw new TypeError("input is valid");
              s(t2, n2, 0, e2);
            }
            var i3;
          }
          function s(t2, e2, i3, a2) {
            const s2 = o[a2 || ""] || o[""];
            n[t2] < n[s2.minimalSeverity] || (s2.logDateTime && (e2 = `${(/* @__PURE__ */ new Date()).toISOString()}|${e2}`), s2.logSourceLocation, r[s2.provider].log(t2, e2, a2));
          }
          !(function(t2) {
            function e2(t3) {
              o = {}, n2("", t3 || {});
            }
            function n2(t3, n3) {
              if ("*" === t3) e2(n3);
              else {
                const e3 = o[t3] || i2;
                o[t3] = { provider: n3.provider || e3.provider, minimalSeverity: n3.minimalSeverity || e3.minimalSeverity, logDateTime: void 0 === n3.logDateTime ? e3.logDateTime : n3.logDateTime, logSourceLocation: void 0 === n3.logSourceLocation ? e3.logSourceLocation : n3.logSourceLocation };
              }
            }
            t2.verbose = function(e3, n3) {
              t2("verbose", e3, n3);
            }, t2.info = function(e3, n3) {
              t2("info", e3, n3);
            }, t2.warning = function(e3, n3) {
              t2("warning", e3, n3);
            }, t2.error = function(e3, n3) {
              t2("error", e3, n3);
            }, t2.fatal = function(e3, n3) {
              t2("fatal", e3, n3);
            }, t2.reset = e2, t2.set = n2, t2.setWithEnv = function(t3) {
              const e3 = {};
              t3.logLevel && (e3.minimalSeverity = t3.logLevel), n2("", e3);
            };
          })(a || (a = {})), e.Logger = a;
          class u {
            constructor(t2, e2, n2, r2, i3, o2) {
              this.category = t2, this.name = e2, this.startTime = n2, this.endCallback = r2, this.timer = i3, this.ctx = o2;
            }
            end() {
              return this.endCallback(this);
            }
            checkTimer() {
              return __async(this, null, function* () {
                if (void 0 === this.ctx || void 0 === this.timer) throw new Error("No webgl timer found");
                return this.ctx.endTimer(), this.ctx.waitForQueryAndGetTime(this.timer);
              });
            }
          }
          class c {
            constructor(t2, e2, n2, r2) {
              this.category = t2, this.name = e2, this.startTime = n2, this.endTime = r2;
            }
          }
          e.Profiler = class {
            static create(t2) {
              return void 0 === t2 ? new this() : new this(t2.maxNumberEvents, t2.flushBatchSize, t2.flushIntervalInMilliseconds);
            }
            constructor(t2, e2, n2) {
              this._started = false, this._flushPointer = 0, this._started = false, this._maxNumberEvents = void 0 === t2 ? 1e4 : t2, this._flushBatchSize = void 0 === e2 ? 10 : e2, this._flushIntervalInMilliseconds = void 0 === n2 ? 5e3 : n2;
            }
            start() {
              this._started = true, this._timingEvents = [], this._flushTime = (0, e.now)(), this._flushPointer = 0;
            }
            stop() {
              for (this._started = false; this._flushPointer < this._timingEvents.length; this._flushPointer++) this.logOneEvent(this._timingEvents[this._flushPointer]);
            }
            event(t2, e2, n2, r2) {
              const i3 = this._started ? this.begin(t2, e2, r2) : void 0;
              let o2 = false;
              const a2 = n2();
              if (a2 && "function" == typeof a2.then) return o2 = true, new Promise(((t3, e3) => {
                a2.then(((e4) => __async(this, null, function* () {
                  i3 && (yield i3.end()), t3(e4);
                })), ((t4) => __async(this, null, function* () {
                  i3 && (yield i3.end()), e3(t4);
                })));
              }));
              if (!o2 && i3) {
                const t3 = i3.end();
                if (t3 && "function" == typeof t3.then) return new Promise(((e3, n3) => {
                  t3.then((() => {
                    e3(a2);
                  }), ((t4) => {
                    n3(t4);
                  }));
                }));
              }
              return a2;
            }
            begin(t2, n2, r2) {
              if (!this._started) throw new Error("profiler is not started yet");
              if (void 0 === r2) {
                const r3 = (0, e.now)();
                return this.flush(r3), new u(t2, n2, r3, ((t3) => this.endSync(t3)));
              }
              {
                const e2 = r2.beginTimer();
                return new u(t2, n2, 0, ((t3) => __async(this, null, function* () {
                  return this.end(t3);
                })), e2, r2);
              }
            }
            end(t2) {
              return __async(this, null, function* () {
                const e2 = yield t2.checkTimer();
                this._timingEvents.length < this._maxNumberEvents && (this._timingEvents.push(new c(t2.category, t2.name, t2.startTime, e2)), this.flush(e2));
              });
            }
            endSync(t2) {
              const n2 = (0, e.now)();
              this._timingEvents.length < this._maxNumberEvents && (this._timingEvents.push(new c(t2.category, t2.name, t2.startTime, n2)), this.flush(n2));
            }
            logOneEvent(t2) {
              e.Logger.verbose(`Profiler.${t2.category}`, `${(t2.endTime - t2.startTime).toFixed(2)}ms on event '${t2.name}' at ${t2.endTime.toFixed(2)}`);
            }
            flush(t2) {
              if (this._timingEvents.length - this._flushPointer >= this._flushBatchSize || t2 - this._flushTime >= this._flushIntervalInMilliseconds) {
                for (const t3 = this._flushPointer; this._flushPointer < t3 + this._flushBatchSize && this._flushPointer < this._timingEvents.length; this._flushPointer++) this.logOneEvent(this._timingEvents[this._flushPointer]);
                this._flushTime = (0, e.now)();
              }
            }
            get started() {
              return this._started;
            }
          }, e.now = "undefined" != typeof performance && performance.now ? () => performance.now() : Date.now;
        }, 2644: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.Model = void 0;
          const r = n(5686), i2 = n(1446), o = n(7070), a = n(9395), s = n(2517);
          var u = a.onnxruntime.experimental.fbs;
          e.Model = class {
            constructor() {
            }
            load(t2, e2, n2) {
              if (!n2) try {
                return void this.loadFromOnnxFormat(t2, e2);
              } catch (t3) {
                if (void 0 !== n2) throw t3;
              }
              this.loadFromOrtFormat(t2, e2);
            }
            loadFromOnnxFormat(t2, e2) {
              const n2 = i2.onnx.ModelProto.decode(t2);
              if (s.LongUtil.longToNumber(n2.irVersion) < 3) throw new Error("only support ONNX model with IR_VERSION>=3");
              this._opsets = n2.opsetImport.map(((t3) => ({ domain: t3.domain, version: s.LongUtil.longToNumber(t3.version) }))), this._graph = o.Graph.from(n2.graph, e2);
            }
            loadFromOrtFormat(t2, e2) {
              const n2 = new r.flatbuffers.ByteBuffer(t2), i3 = u.InferenceSession.getRootAsInferenceSession(n2).model();
              if (s.LongUtil.longToNumber(i3.irVersion()) < 3) throw new Error("only support ONNX model with IR_VERSION>=3");
              this._opsets = [];
              for (let t3 = 0; t3 < i3.opsetImportLength(); t3++) {
                const e3 = i3.opsetImport(t3);
                this._opsets.push({ domain: null == e3 ? void 0 : e3.domain(), version: s.LongUtil.longToNumber(e3.version()) });
              }
              this._graph = o.Graph.from(i3.graph(), e2);
            }
            get graph() {
              return this._graph;
            }
            get opsets() {
              return this._opsets;
            }
          };
        }, 782: (t, e) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.FLOAT_TYPES = e.INT_TYPES = e.NUMBER_TYPES = void 0, e.NUMBER_TYPES = ["float32", "float64", "int32", "int16", "int8", "uint16", "uint32", "uint8"], e.INT_TYPES = ["int32", "int16", "int8", "uint16", "uint32", "uint8"], e.FLOAT_TYPES = ["float32", "float64"];
        }, 1047: (t, e) => {
          function n(t2, e2) {
            if (e2.endsWith("+")) {
              const n2 = Number.parseInt(e2.substring(0, e2.length - 1), 10);
              return !isNaN(n2) && n2 <= t2;
            }
            if (2 === e2.split("-").length) {
              const n2 = e2.split("-"), r = Number.parseInt(n2[0], 10), i2 = Number.parseInt(n2[1], 10);
              return !isNaN(r) && !isNaN(i2) && r <= t2 && t2 <= i2;
            }
            return Number.parseInt(e2, 10) === t2;
          }
          Object.defineProperty(e, "__esModule", { value: true }), e.resolveOperator = void 0, e.resolveOperator = function(t2, e2, r) {
            for (const i2 of r) {
              const r2 = i2[0], o = i2[1], a = i2[2], s = i2[3], u = i2[4];
              if (t2.opType === r2) {
                for (const t3 of e2) if ((t3.domain === o || "ai.onnx" === t3.domain && "" === o) && n(t3.version, a)) return { opImpl: s, opInit: u };
              }
            }
            throw new TypeError(`cannot resolve operator '${t2.opType}' with opsets: ${e2.map(((t3) => `${t3.domain || "ai.onnx"} v${t3.version}`)).join(", ")}`);
          };
        }, 9395: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.onnxruntime = void 0;
          const r = n(5686);
          var i2, o;
          i2 = e.onnxruntime || (e.onnxruntime = {}), (function(t2) {
            !(function(t3) {
              t3[t3.UNDEFINED = 0] = "UNDEFINED", t3[t3.FLOAT = 1] = "FLOAT", t3[t3.INT = 2] = "INT", t3[t3.STRING = 3] = "STRING", t3[t3.TENSOR = 4] = "TENSOR", t3[t3.GRAPH = 5] = "GRAPH", t3[t3.FLOATS = 6] = "FLOATS", t3[t3.INTS = 7] = "INTS", t3[t3.STRINGS = 8] = "STRINGS", t3[t3.TENSORS = 9] = "TENSORS", t3[t3.GRAPHS = 10] = "GRAPHS", t3[t3.SPARSE_TENSOR = 11] = "SPARSE_TENSOR", t3[t3.SPARSE_TENSORS = 12] = "SPARSE_TENSORS";
            })(t2.AttributeType || (t2.AttributeType = {}));
          })((o = i2.experimental || (i2.experimental = {})).fbs || (o.fbs = {})), (function(t2) {
            !(function(t3) {
              !(function(t4) {
                !(function(t5) {
                  t5[t5.UNKNOWN = 0] = "UNKNOWN", t5[t5.VALUE = 1] = "VALUE", t5[t5.PARAM = 2] = "PARAM";
                })(t4.DimensionValueType || (t4.DimensionValueType = {}));
              })(t3.fbs || (t3.fbs = {}));
            })(t2.experimental || (t2.experimental = {}));
          })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) {
            !(function(t3) {
              !(function(t4) {
                !(function(t5) {
                  t5[t5.UNDEFINED = 0] = "UNDEFINED", t5[t5.FLOAT = 1] = "FLOAT", t5[t5.UINT8 = 2] = "UINT8", t5[t5.INT8 = 3] = "INT8", t5[t5.UINT16 = 4] = "UINT16", t5[t5.INT16 = 5] = "INT16", t5[t5.INT32 = 6] = "INT32", t5[t5.INT64 = 7] = "INT64", t5[t5.STRING = 8] = "STRING", t5[t5.BOOL = 9] = "BOOL", t5[t5.FLOAT16 = 10] = "FLOAT16", t5[t5.DOUBLE = 11] = "DOUBLE", t5[t5.UINT32 = 12] = "UINT32", t5[t5.UINT64 = 13] = "UINT64", t5[t5.COMPLEX64 = 14] = "COMPLEX64", t5[t5.COMPLEX128 = 15] = "COMPLEX128", t5[t5.BFLOAT16 = 16] = "BFLOAT16";
                })(t4.TensorDataType || (t4.TensorDataType = {}));
              })(t3.fbs || (t3.fbs = {}));
            })(t2.experimental || (t2.experimental = {}));
          })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) {
            !(function(t3) {
              !(function(t4) {
                !(function(t5) {
                  t5[t5.Primitive = 0] = "Primitive", t5[t5.Fused = 1] = "Fused";
                })(t4.NodeType || (t4.NodeType = {}));
              })(t3.fbs || (t3.fbs = {}));
            })(t2.experimental || (t2.experimental = {}));
          })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) {
            !(function(t3) {
              !(function(t4) {
                !(function(t5) {
                  t5[t5.NONE = 0] = "NONE", t5[t5.tensor_type = 1] = "tensor_type", t5[t5.sequence_type = 2] = "sequence_type", t5[t5.map_type = 3] = "map_type";
                })(t4.TypeInfoValue || (t4.TypeInfoValue = {}));
              })(t3.fbs || (t3.fbs = {}));
            })(t2.experimental || (t2.experimental = {}));
          })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) {
            !(function(e2) {
              !(function(e3) {
                class n2 {
                  constructor() {
                    this.bb = null, this.bb_pos = 0;
                  }
                  __init(t3, e4) {
                    return this.bb_pos = t3, this.bb = e4, this;
                  }
                  static getRootAsShape(t3, e4) {
                    return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
                  }
                  static getSizePrefixedRootAsShape(t3, e4) {
                    return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
                  }
                  dim(e4, n3) {
                    let r2 = this.bb.__offset(this.bb_pos, 4);
                    return r2 ? (n3 || new t2.experimental.fbs.Dimension()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null;
                  }
                  dimLength() {
                    let t3 = this.bb.__offset(this.bb_pos, 4);
                    return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
                  }
                  static startShape(t3) {
                    t3.startObject(1);
                  }
                  static addDim(t3, e4) {
                    t3.addFieldOffset(0, e4, 0);
                  }
                  static createDimVector(t3, e4) {
                    t3.startVector(4, e4.length, 4);
                    for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addOffset(e4[n3]);
                    return t3.endVector();
                  }
                  static startDimVector(t3, e4) {
                    t3.startVector(4, e4, 4);
                  }
                  static endShape(t3) {
                    return t3.endObject();
                  }
                  static createShape(t3, e4) {
                    return n2.startShape(t3), n2.addDim(t3, e4), n2.endShape(t3);
                  }
                }
                e3.Shape = n2;
              })(e2.fbs || (e2.fbs = {}));
            })(t2.experimental || (t2.experimental = {}));
          })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) {
            !(function(e2) {
              !(function(e3) {
                class n2 {
                  constructor() {
                    this.bb = null, this.bb_pos = 0;
                  }
                  __init(t3, e4) {
                    return this.bb_pos = t3, this.bb = e4, this;
                  }
                  static getRootAsDimension(t3, e4) {
                    return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
                  }
                  static getSizePrefixedRootAsDimension(t3, e4) {
                    return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
                  }
                  value(e4) {
                    let n3 = this.bb.__offset(this.bb_pos, 4);
                    return n3 ? (e4 || new t2.experimental.fbs.DimensionValue()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null;
                  }
                  denotation(t3) {
                    let e4 = this.bb.__offset(this.bb_pos, 6);
                    return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
                  }
                  static startDimension(t3) {
                    t3.startObject(2);
                  }
                  static addValue(t3, e4) {
                    t3.addFieldOffset(0, e4, 0);
                  }
                  static addDenotation(t3, e4) {
                    t3.addFieldOffset(1, e4, 0);
                  }
                  static endDimension(t3) {
                    return t3.endObject();
                  }
                  static createDimension(t3, e4, r2) {
                    return n2.startDimension(t3), n2.addValue(t3, e4), n2.addDenotation(t3, r2), n2.endDimension(t3);
                  }
                }
                e3.Dimension = n2;
              })(e2.fbs || (e2.fbs = {}));
            })(t2.experimental || (t2.experimental = {}));
          })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) {
            !(function(e2) {
              !(function(e3) {
                class n2 {
                  constructor() {
                    this.bb = null, this.bb_pos = 0;
                  }
                  __init(t3, e4) {
                    return this.bb_pos = t3, this.bb = e4, this;
                  }
                  static getRootAsDimensionValue(t3, e4) {
                    return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
                  }
                  static getSizePrefixedRootAsDimensionValue(t3, e4) {
                    return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
                  }
                  dimType() {
                    let e4 = this.bb.__offset(this.bb_pos, 4);
                    return e4 ? this.bb.readInt8(this.bb_pos + e4) : t2.experimental.fbs.DimensionValueType.UNKNOWN;
                  }
                  dimValue() {
                    let t3 = this.bb.__offset(this.bb_pos, 6);
                    return t3 ? this.bb.readInt64(this.bb_pos + t3) : this.bb.createLong(0, 0);
                  }
                  dimParam(t3) {
                    let e4 = this.bb.__offset(this.bb_pos, 8);
                    return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
                  }
                  static startDimensionValue(t3) {
                    t3.startObject(3);
                  }
                  static addDimType(e4, n3) {
                    e4.addFieldInt8(0, n3, t2.experimental.fbs.DimensionValueType.UNKNOWN);
                  }
                  static addDimValue(t3, e4) {
                    t3.addFieldInt64(1, e4, t3.createLong(0, 0));
                  }
                  static addDimParam(t3, e4) {
                    t3.addFieldOffset(2, e4, 0);
                  }
                  static endDimensionValue(t3) {
                    return t3.endObject();
                  }
                  static createDimensionValue(t3, e4, r2, i3) {
                    return n2.startDimensionValue(t3), n2.addDimType(t3, e4), n2.addDimValue(t3, r2), n2.addDimParam(t3, i3), n2.endDimensionValue(t3);
                  }
                }
                e3.DimensionValue = n2;
              })(e2.fbs || (e2.fbs = {}));
            })(t2.experimental || (t2.experimental = {}));
          })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) {
            !(function(e2) {
              !(function(e3) {
                class n2 {
                  constructor() {
                    this.bb = null, this.bb_pos = 0;
                  }
                  __init(t3, e4) {
                    return this.bb_pos = t3, this.bb = e4, this;
                  }
                  static getRootAsTensorTypeAndShape(t3, e4) {
                    return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
                  }
                  static getSizePrefixedRootAsTensorTypeAndShape(t3, e4) {
                    return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
                  }
                  elemType() {
                    let e4 = this.bb.__offset(this.bb_pos, 4);
                    return e4 ? this.bb.readInt32(this.bb_pos + e4) : t2.experimental.fbs.TensorDataType.UNDEFINED;
                  }
                  shape(e4) {
                    let n3 = this.bb.__offset(this.bb_pos, 6);
                    return n3 ? (e4 || new t2.experimental.fbs.Shape()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null;
                  }
                  static startTensorTypeAndShape(t3) {
                    t3.startObject(2);
                  }
                  static addElemType(e4, n3) {
                    e4.addFieldInt32(0, n3, t2.experimental.fbs.TensorDataType.UNDEFINED);
                  }
                  static addShape(t3, e4) {
                    t3.addFieldOffset(1, e4, 0);
                  }
                  static endTensorTypeAndShape(t3) {
                    return t3.endObject();
                  }
                  static createTensorTypeAndShape(t3, e4, r2) {
                    return n2.startTensorTypeAndShape(t3), n2.addElemType(t3, e4), n2.addShape(t3, r2), n2.endTensorTypeAndShape(t3);
                  }
                }
                e3.TensorTypeAndShape = n2;
              })(e2.fbs || (e2.fbs = {}));
            })(t2.experimental || (t2.experimental = {}));
          })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) {
            !(function(e2) {
              !(function(e3) {
                class n2 {
                  constructor() {
                    this.bb = null, this.bb_pos = 0;
                  }
                  __init(t3, e4) {
                    return this.bb_pos = t3, this.bb = e4, this;
                  }
                  static getRootAsMapType(t3, e4) {
                    return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
                  }
                  static getSizePrefixedRootAsMapType(t3, e4) {
                    return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
                  }
                  keyType() {
                    let e4 = this.bb.__offset(this.bb_pos, 4);
                    return e4 ? this.bb.readInt32(this.bb_pos + e4) : t2.experimental.fbs.TensorDataType.UNDEFINED;
                  }
                  valueType(e4) {
                    let n3 = this.bb.__offset(this.bb_pos, 6);
                    return n3 ? (e4 || new t2.experimental.fbs.TypeInfo()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null;
                  }
                  static startMapType(t3) {
                    t3.startObject(2);
                  }
                  static addKeyType(e4, n3) {
                    e4.addFieldInt32(0, n3, t2.experimental.fbs.TensorDataType.UNDEFINED);
                  }
                  static addValueType(t3, e4) {
                    t3.addFieldOffset(1, e4, 0);
                  }
                  static endMapType(t3) {
                    return t3.endObject();
                  }
                  static createMapType(t3, e4, r2) {
                    return n2.startMapType(t3), n2.addKeyType(t3, e4), n2.addValueType(t3, r2), n2.endMapType(t3);
                  }
                }
                e3.MapType = n2;
              })(e2.fbs || (e2.fbs = {}));
            })(t2.experimental || (t2.experimental = {}));
          })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) {
            !(function(e2) {
              !(function(e3) {
                class n2 {
                  constructor() {
                    this.bb = null, this.bb_pos = 0;
                  }
                  __init(t3, e4) {
                    return this.bb_pos = t3, this.bb = e4, this;
                  }
                  static getRootAsSequenceType(t3, e4) {
                    return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
                  }
                  static getSizePrefixedRootAsSequenceType(t3, e4) {
                    return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
                  }
                  elemType(e4) {
                    let n3 = this.bb.__offset(this.bb_pos, 4);
                    return n3 ? (e4 || new t2.experimental.fbs.TypeInfo()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null;
                  }
                  static startSequenceType(t3) {
                    t3.startObject(1);
                  }
                  static addElemType(t3, e4) {
                    t3.addFieldOffset(0, e4, 0);
                  }
                  static endSequenceType(t3) {
                    return t3.endObject();
                  }
                  static createSequenceType(t3, e4) {
                    return n2.startSequenceType(t3), n2.addElemType(t3, e4), n2.endSequenceType(t3);
                  }
                }
                e3.SequenceType = n2;
              })(e2.fbs || (e2.fbs = {}));
            })(t2.experimental || (t2.experimental = {}));
          })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) {
            !(function(t3) {
              (t3.fbs || (t3.fbs = {})).EdgeEnd = class {
                constructor() {
                  this.bb = null, this.bb_pos = 0;
                }
                __init(t4, e2) {
                  return this.bb_pos = t4, this.bb = e2, 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 createEdgeEnd(t4, e2, n2, r2) {
                  return t4.prep(4, 12), t4.writeInt32(r2), t4.writeInt32(n2), t4.writeInt32(e2), t4.offset();
                }
              };
            })(t2.experimental || (t2.experimental = {}));
          })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) {
            !(function(e2) {
              !(function(e3) {
                class n2 {
                  constructor() {
                    this.bb = null, this.bb_pos = 0;
                  }
                  __init(t3, e4) {
                    return this.bb_pos = t3, this.bb = e4, this;
                  }
                  static getRootAsNodeEdge(t3, e4) {
                    return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
                  }
                  static getSizePrefixedRootAsNodeEdge(t3, e4) {
                    return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
                  }
                  nodeIndex() {
                    let t3 = this.bb.__offset(this.bb_pos, 4);
                    return t3 ? this.bb.readUint32(this.bb_pos + t3) : 0;
                  }
                  inputEdges(e4, n3) {
                    let r2 = this.bb.__offset(this.bb_pos, 6);
                    return r2 ? (n3 || new t2.experimental.fbs.EdgeEnd()).__init(this.bb.__vector(this.bb_pos + r2) + 12 * e4, this.bb) : null;
                  }
                  inputEdgesLength() {
                    let t3 = this.bb.__offset(this.bb_pos, 6);
                    return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
                  }
                  outputEdges(e4, n3) {
                    let r2 = this.bb.__offset(this.bb_pos, 8);
                    return r2 ? (n3 || new t2.experimental.fbs.EdgeEnd()).__init(this.bb.__vector(this.bb_pos + r2) + 12 * e4, this.bb) : null;
                  }
                  outputEdgesLength() {
                    let t3 = this.bb.__offset(this.bb_pos, 8);
                    return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
                  }
                  static startNodeEdge(t3) {
                    t3.startObject(3);
                  }
                  static addNodeIndex(t3, e4) {
                    t3.addFieldInt32(0, e4, 0);
                  }
                  static addInputEdges(t3, e4) {
                    t3.addFieldOffset(1, e4, 0);
                  }
                  static startInputEdgesVector(t3, e4) {
                    t3.startVector(12, e4, 4);
                  }
                  static addOutputEdges(t3, e4) {
                    t3.addFieldOffset(2, e4, 0);
                  }
                  static startOutputEdgesVector(t3, e4) {
                    t3.startVector(12, e4, 4);
                  }
                  static endNodeEdge(t3) {
                    return t3.endObject();
                  }
                  static createNodeEdge(t3, e4, r2, i3) {
                    return n2.startNodeEdge(t3), n2.addNodeIndex(t3, e4), n2.addInputEdges(t3, r2), n2.addOutputEdges(t3, i3), n2.endNodeEdge(t3);
                  }
                }
                e3.NodeEdge = n2;
              })(e2.fbs || (e2.fbs = {}));
            })(t2.experimental || (t2.experimental = {}));
          })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) {
            !(function(e2) {
              !(function(e3) {
                class n2 {
                  constructor() {
                    this.bb = null, this.bb_pos = 0;
                  }
                  __init(t3, e4) {
                    return this.bb_pos = t3, this.bb = e4, this;
                  }
                  static getRootAsNode(t3, e4) {
                    return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
                  }
                  static getSizePrefixedRootAsNode(t3, e4) {
                    return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
                  }
                  name(t3) {
                    let e4 = this.bb.__offset(this.bb_pos, 4);
                    return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
                  }
                  docString(t3) {
                    let e4 = this.bb.__offset(this.bb_pos, 6);
                    return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
                  }
                  domain(t3) {
                    let e4 = this.bb.__offset(this.bb_pos, 8);
                    return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
                  }
                  sinceVersion() {
                    let t3 = this.bb.__offset(this.bb_pos, 10);
                    return t3 ? this.bb.readInt32(this.bb_pos + t3) : 0;
                  }
                  index() {
                    let t3 = this.bb.__offset(this.bb_pos, 12);
                    return t3 ? this.bb.readUint32(this.bb_pos + t3) : 0;
                  }
                  opType(t3) {
                    let e4 = this.bb.__offset(this.bb_pos, 14);
                    return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
                  }
                  type() {
                    let e4 = this.bb.__offset(this.bb_pos, 16);
                    return e4 ? this.bb.readInt32(this.bb_pos + e4) : t2.experimental.fbs.NodeType.Primitive;
                  }
                  executionProviderType(t3) {
                    let e4 = this.bb.__offset(this.bb_pos, 18);
                    return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
                  }
                  inputs(t3, e4) {
                    let n3 = this.bb.__offset(this.bb_pos, 20);
                    return n3 ? this.bb.__string(this.bb.__vector(this.bb_pos + n3) + 4 * t3, e4) : null;
                  }
                  inputsLength() {
                    let t3 = this.bb.__offset(this.bb_pos, 20);
                    return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
                  }
                  outputs(t3, e4) {
                    let n3 = this.bb.__offset(this.bb_pos, 22);
                    return n3 ? this.bb.__string(this.bb.__vector(this.bb_pos + n3) + 4 * t3, e4) : null;
                  }
                  outputsLength() {
                    let t3 = this.bb.__offset(this.bb_pos, 22);
                    return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
                  }
                  attributes(e4, n3) {
                    let r2 = this.bb.__offset(this.bb_pos, 24);
                    return r2 ? (n3 || new t2.experimental.fbs.Attribute()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null;
                  }
                  attributesLength() {
                    let t3 = this.bb.__offset(this.bb_pos, 24);
                    return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
                  }
                  inputArgCounts(t3) {
                    let e4 = this.bb.__offset(this.bb_pos, 26);
                    return e4 ? this.bb.readInt32(this.bb.__vector(this.bb_pos + e4) + 4 * t3) : 0;
                  }
                  inputArgCountsLength() {
                    let t3 = this.bb.__offset(this.bb_pos, 26);
                    return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
                  }
                  inputArgCountsArray() {
                    let t3 = this.bb.__offset(this.bb_pos, 26);
                    return t3 ? new Int32Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + t3), this.bb.__vector_len(this.bb_pos + t3)) : null;
                  }
                  implicitInputs(t3, e4) {
                    let n3 = this.bb.__offset(this.bb_pos, 28);
                    return n3 ? this.bb.__string(this.bb.__vector(this.bb_pos + n3) + 4 * t3, e4) : null;
                  }
                  implicitInputsLength() {
                    let t3 = this.bb.__offset(this.bb_pos, 28);
                    return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
                  }
                  static startNode(t3) {
                    t3.startObject(13);
                  }
                  static addName(t3, e4) {
                    t3.addFieldOffset(0, e4, 0);
                  }
                  static addDocString(t3, e4) {
                    t3.addFieldOffset(1, e4, 0);
                  }
                  static addDomain(t3, e4) {
                    t3.addFieldOffset(2, e4, 0);
                  }
                  static addSinceVersion(t3, e4) {
                    t3.addFieldInt32(3, e4, 0);
                  }
                  static addIndex(t3, e4) {
                    t3.addFieldInt32(4, e4, 0);
                  }
                  static addOpType(t3, e4) {
                    t3.addFieldOffset(5, e4, 0);
                  }
                  static addType(e4, n3) {
                    e4.addFieldInt32(6, n3, t2.experimental.fbs.NodeType.Primitive);
                  }
                  static addExecutionProviderType(t3, e4) {
                    t3.addFieldOffset(7, e4, 0);
                  }
                  static addInputs(t3, e4) {
                    t3.addFieldOffset(8, e4, 0);
                  }
                  static createInputsVector(t3, e4) {
                    t3.startVector(4, e4.length, 4);
                    for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addOffset(e4[n3]);
                    return t3.endVector();
                  }
                  static startInputsVector(t3, e4) {
                    t3.startVector(4, e4, 4);
                  }
                  static addOutputs(t3, e4) {
                    t3.addFieldOffset(9, e4, 0);
                  }
                  static createOutputsVector(t3, e4) {
                    t3.startVector(4, e4.length, 4);
                    for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addOffset(e4[n3]);
                    return t3.endVector();
                  }
                  static startOutputsVector(t3, e4) {
                    t3.startVector(4, e4, 4);
                  }
                  static addAttributes(t3, e4) {
                    t3.addFieldOffset(10, e4, 0);
                  }
                  static createAttributesVector(t3, e4) {
                    t3.startVector(4, e4.length, 4);
                    for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addOffset(e4[n3]);
                    return t3.endVector();
                  }
                  static startAttributesVector(t3, e4) {
                    t3.startVector(4, e4, 4);
                  }
                  static addInputArgCounts(t3, e4) {
                    t3.addFieldOffset(11, e4, 0);
                  }
                  static createInputArgCountsVector(t3, e4) {
                    t3.startVector(4, e4.length, 4);
                    for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addInt32(e4[n3]);
                    return t3.endVector();
                  }
                  static startInputArgCountsVector(t3, e4) {
                    t3.startVector(4, e4, 4);
                  }
                  static addImplicitInputs(t3, e4) {
                    t3.addFieldOffset(12, e4, 0);
                  }
                  static createImplicitInputsVector(t3, e4) {
                    t3.startVector(4, e4.length, 4);
                    for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addOffset(e4[n3]);
                    return t3.endVector();
                  }
                  static startImplicitInputsVector(t3, e4) {
                    t3.startVector(4, e4, 4);
                  }
                  static endNode(t3) {
                    return t3.endObject();
                  }
                  static createNode(t3, e4, r2, i3, o2, a, s, u, c, l, p, f, d, h) {
                    return n2.startNode(t3), n2.addName(t3, e4), n2.addDocString(t3, r2), n2.addDomain(t3, i3), n2.addSinceVersion(t3, o2), n2.addIndex(t3, a), n2.addOpType(t3, s), n2.addType(t3, u), n2.addExecutionProviderType(t3, c), n2.addInputs(t3, l), n2.addOutputs(t3, p), n2.addAttributes(t3, f), n2.addInputArgCounts(t3, d), n2.addImplicitInputs(t3, h), n2.endNode(t3);
                  }
                }
                e3.Node = n2;
              })(e2.fbs || (e2.fbs = {}));
            })(t2.experimental || (t2.experimental = {}));
          })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) {
            !(function(e2) {
              !(function(e3) {
                class n2 {
                  constructor() {
                    this.bb = null, this.bb_pos = 0;
                  }
                  __init(t3, e4) {
                    return this.bb_pos = t3, this.bb = e4, this;
                  }
                  static getRootAsValueInfo(t3, e4) {
                    return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
                  }
                  static getSizePrefixedRootAsValueInfo(t3, e4) {
                    return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
                  }
                  name(t3) {
                    let e4 = this.bb.__offset(this.bb_pos, 4);
                    return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
                  }
                  docString(t3) {
                    let e4 = this.bb.__offset(this.bb_pos, 6);
                    return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
                  }
                  type(e4) {
                    let n3 = this.bb.__offset(this.bb_pos, 8);
                    return n3 ? (e4 || new t2.experimental.fbs.TypeInfo()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null;
                  }
                  static startValueInfo(t3) {
                    t3.startObject(3);
                  }
                  static addName(t3, e4) {
                    t3.addFieldOffset(0, e4, 0);
                  }
                  static addDocString(t3, e4) {
                    t3.addFieldOffset(1, e4, 0);
                  }
                  static addType(t3, e4) {
                    t3.addFieldOffset(2, e4, 0);
                  }
                  static endValueInfo(t3) {
                    return t3.endObject();
                  }
                  static createValueInfo(t3, e4, r2, i3) {
                    return n2.startValueInfo(t3), n2.addName(t3, e4), n2.addDocString(t3, r2), n2.addType(t3, i3), n2.endValueInfo(t3);
                  }
                }
                e3.ValueInfo = n2;
              })(e2.fbs || (e2.fbs = {}));
            })(t2.experimental || (t2.experimental = {}));
          })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) {
            !(function(e2) {
              !(function(e3) {
                class n2 {
                  constructor() {
                    this.bb = null, this.bb_pos = 0;
                  }
                  __init(t3, e4) {
                    return this.bb_pos = t3, this.bb = e4, this;
                  }
                  static getRootAsTypeInfo(t3, e4) {
                    return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
                  }
                  static getSizePrefixedRootAsTypeInfo(t3, e4) {
                    return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
                  }
                  denotation(t3) {
                    let e4 = this.bb.__offset(this.bb_pos, 4);
                    return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
                  }
                  valueType() {
                    let e4 = this.bb.__offset(this.bb_pos, 6);
                    return e4 ? this.bb.readUint8(this.bb_pos + e4) : t2.experimental.fbs.TypeInfoValue.NONE;
                  }
                  value(t3) {
                    let e4 = this.bb.__offset(this.bb_pos, 8);
                    return e4 ? this.bb.__union(t3, this.bb_pos + e4) : null;
                  }
                  static startTypeInfo(t3) {
                    t3.startObject(3);
                  }
                  static addDenotation(t3, e4) {
                    t3.addFieldOffset(0, e4, 0);
                  }
                  static addValueType(e4, n3) {
                    e4.addFieldInt8(1, n3, t2.experimental.fbs.TypeInfoValue.NONE);
                  }
                  static addValue(t3, e4) {
                    t3.addFieldOffset(2, e4, 0);
                  }
                  static endTypeInfo(t3) {
                    return t3.endObject();
                  }
                  static createTypeInfo(t3, e4, r2, i3) {
                    return n2.startTypeInfo(t3), n2.addDenotation(t3, e4), n2.addValueType(t3, r2), n2.addValue(t3, i3), n2.endTypeInfo(t3);
                  }
                }
                e3.TypeInfo = n2;
              })(e2.fbs || (e2.fbs = {}));
            })(t2.experimental || (t2.experimental = {}));
          })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) {
            !(function(t3) {
              !(function(t4) {
                class e2 {
                  constructor() {
                    this.bb = null, this.bb_pos = 0;
                  }
                  __init(t5, e3) {
                    return this.bb_pos = t5, this.bb = e3, this;
                  }
                  static getRootAsOperatorSetId(t5, n2) {
                    return (n2 || new e2()).__init(t5.readInt32(t5.position()) + t5.position(), t5);
                  }
                  static getSizePrefixedRootAsOperatorSetId(t5, n2) {
                    return t5.setPosition(t5.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (n2 || new e2()).__init(t5.readInt32(t5.position()) + t5.position(), t5);
                  }
                  domain(t5) {
                    let e3 = this.bb.__offset(this.bb_pos, 4);
                    return e3 ? this.bb.__string(this.bb_pos + e3, t5) : null;
                  }
                  version() {
                    let t5 = this.bb.__offset(this.bb_pos, 6);
                    return t5 ? this.bb.readInt64(this.bb_pos + t5) : this.bb.createLong(0, 0);
                  }
                  static startOperatorSetId(t5) {
                    t5.startObject(2);
                  }
                  static addDomain(t5, e3) {
                    t5.addFieldOffset(0, e3, 0);
                  }
                  static addVersion(t5, e3) {
                    t5.addFieldInt64(1, e3, t5.createLong(0, 0));
                  }
                  static endOperatorSetId(t5) {
                    return t5.endObject();
                  }
                  static createOperatorSetId(t5, n2, r2) {
                    return e2.startOperatorSetId(t5), e2.addDomain(t5, n2), e2.addVersion(t5, r2), e2.endOperatorSetId(t5);
                  }
                }
                t4.OperatorSetId = e2;
              })(t3.fbs || (t3.fbs = {}));
            })(t2.experimental || (t2.experimental = {}));
          })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) {
            !(function(e2) {
              !(function(e3) {
                class n2 {
                  constructor() {
                    this.bb = null, this.bb_pos = 0;
                  }
                  __init(t3, e4) {
                    return this.bb_pos = t3, this.bb = e4, this;
                  }
                  static getRootAsTensor(t3, e4) {
                    return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
                  }
                  static getSizePrefixedRootAsTensor(t3, e4) {
                    return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
                  }
                  name(t3) {
                    let e4 = this.bb.__offset(this.bb_pos, 4);
                    return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
                  }
                  docString(t3) {
                    let e4 = this.bb.__offset(this.bb_pos, 6);
                    return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
                  }
                  dims(t3) {
                    let e4 = this.bb.__offset(this.bb_pos, 8);
                    return e4 ? this.bb.readInt64(this.bb.__vector(this.bb_pos + e4) + 8 * t3) : this.bb.createLong(0, 0);
                  }
                  dimsLength() {
                    let t3 = this.bb.__offset(this.bb_pos, 8);
                    return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
                  }
                  dataType() {
                    let e4 = this.bb.__offset(this.bb_pos, 10);
                    return e4 ? this.bb.readInt32(this.bb_pos + e4) : t2.experimental.fbs.TensorDataType.UNDEFINED;
                  }
                  rawData(t3) {
                    let e4 = this.bb.__offset(this.bb_pos, 12);
                    return e4 ? this.bb.readUint8(this.bb.__vector(this.bb_pos + e4) + t3) : 0;
                  }
                  rawDataLength() {
                    let t3 = this.bb.__offset(this.bb_pos, 12);
                    return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
                  }
                  rawDataArray() {
                    let t3 = this.bb.__offset(this.bb_pos, 12);
                    return t3 ? new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + t3), this.bb.__vector_len(this.bb_pos + t3)) : null;
                  }
                  stringData(t3, e4) {
                    let n3 = this.bb.__offset(this.bb_pos, 14);
                    return n3 ? this.bb.__string(this.bb.__vector(this.bb_pos + n3) + 4 * t3, e4) : null;
                  }
                  stringDataLength() {
                    let t3 = this.bb.__offset(this.bb_pos, 14);
                    return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
                  }
                  static startTensor(t3) {
                    t3.startObject(6);
                  }
                  static addName(t3, e4) {
                    t3.addFieldOffset(0, e4, 0);
                  }
                  static addDocString(t3, e4) {
                    t3.addFieldOffset(1, e4, 0);
                  }
                  static addDims(t3, e4) {
                    t3.addFieldOffset(2, e4, 0);
                  }
                  static createDimsVector(t3, e4) {
                    t3.startVector(8, e4.length, 8);
                    for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addInt64(e4[n3]);
                    return t3.endVector();
                  }
                  static startDimsVector(t3, e4) {
                    t3.startVector(8, e4, 8);
                  }
                  static addDataType(e4, n3) {
                    e4.addFieldInt32(3, n3, t2.experimental.fbs.TensorDataType.UNDEFINED);
                  }
                  static addRawData(t3, e4) {
                    t3.addFieldOffset(4, e4, 0);
                  }
                  static createRawDataVector(t3, e4) {
                    t3.startVector(1, e4.length, 1);
                    for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addInt8(e4[n3]);
                    return t3.endVector();
                  }
                  static startRawDataVector(t3, e4) {
                    t3.startVector(1, e4, 1);
                  }
                  static addStringData(t3, e4) {
                    t3.addFieldOffset(5, e4, 0);
                  }
                  static createStringDataVector(t3, e4) {
                    t3.startVector(4, e4.length, 4);
                    for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addOffset(e4[n3]);
                    return t3.endVector();
                  }
                  static startStringDataVector(t3, e4) {
                    t3.startVector(4, e4, 4);
                  }
                  static endTensor(t3) {
                    return t3.endObject();
                  }
                  static createTensor(t3, e4, r2, i3, o2, a, s) {
                    return n2.startTensor(t3), n2.addName(t3, e4), n2.addDocString(t3, r2), n2.addDims(t3, i3), n2.addDataType(t3, o2), n2.addRawData(t3, a), n2.addStringData(t3, s), n2.endTensor(t3);
                  }
                }
                e3.Tensor = n2;
              })(e2.fbs || (e2.fbs = {}));
            })(t2.experimental || (t2.experimental = {}));
          })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) {
            !(function(e2) {
              !(function(e3) {
                class n2 {
                  constructor() {
                    this.bb = null, this.bb_pos = 0;
                  }
                  __init(t3, e4) {
                    return this.bb_pos = t3, this.bb = e4, this;
                  }
                  static getRootAsSparseTensor(t3, e4) {
                    return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
                  }
                  static getSizePrefixedRootAsSparseTensor(t3, e4) {
                    return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
                  }
                  values(e4) {
                    let n3 = this.bb.__offset(this.bb_pos, 4);
                    return n3 ? (e4 || new t2.experimental.fbs.Tensor()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null;
                  }
                  indices(e4) {
                    let n3 = this.bb.__offset(this.bb_pos, 6);
                    return n3 ? (e4 || new t2.experimental.fbs.Tensor()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null;
                  }
                  dims(t3) {
                    let e4 = this.bb.__offset(this.bb_pos, 8);
                    return e4 ? this.bb.readInt64(this.bb.__vector(this.bb_pos + e4) + 8 * t3) : this.bb.createLong(0, 0);
                  }
                  dimsLength() {
                    let t3 = this.bb.__offset(this.bb_pos, 8);
                    return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
                  }
                  static startSparseTensor(t3) {
                    t3.startObject(3);
                  }
                  static addValues(t3, e4) {
                    t3.addFieldOffset(0, e4, 0);
                  }
                  static addIndices(t3, e4) {
                    t3.addFieldOffset(1, e4, 0);
                  }
                  static addDims(t3, e4) {
                    t3.addFieldOffset(2, e4, 0);
                  }
                  static createDimsVector(t3, e4) {
                    t3.startVector(8, e4.length, 8);
                    for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addInt64(e4[n3]);
                    return t3.endVector();
                  }
                  static startDimsVector(t3, e4) {
                    t3.startVector(8, e4, 8);
                  }
                  static endSparseTensor(t3) {
                    return t3.endObject();
                  }
                  static createSparseTensor(t3, e4, r2, i3) {
                    return n2.startSparseTensor(t3), n2.addValues(t3, e4), n2.addIndices(t3, r2), n2.addDims(t3, i3), n2.endSparseTensor(t3);
                  }
                }
                e3.SparseTensor = n2;
              })(e2.fbs || (e2.fbs = {}));
            })(t2.experimental || (t2.experimental = {}));
          })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) {
            !(function(e2) {
              !(function(e3) {
                class n2 {
                  constructor() {
                    this.bb = null, this.bb_pos = 0;
                  }
                  __init(t3, e4) {
                    return this.bb_pos = t3, this.bb = e4, this;
                  }
                  static getRootAsAttribute(t3, e4) {
                    return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
                  }
                  static getSizePrefixedRootAsAttribute(t3, e4) {
                    return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
                  }
                  name(t3) {
                    let e4 = this.bb.__offset(this.bb_pos, 4);
                    return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
                  }
                  docString(t3) {
                    let e4 = this.bb.__offset(this.bb_pos, 6);
                    return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
                  }
                  type() {
                    let e4 = this.bb.__offset(this.bb_pos, 8);
                    return e4 ? this.bb.readInt32(this.bb_pos + e4) : t2.experimental.fbs.AttributeType.UNDEFINED;
                  }
                  f() {
                    let t3 = this.bb.__offset(this.bb_pos, 10);
                    return t3 ? this.bb.readFloat32(this.bb_pos + t3) : 0;
                  }
                  i() {
                    let t3 = this.bb.__offset(this.bb_pos, 12);
                    return t3 ? this.bb.readInt64(this.bb_pos + t3) : this.bb.createLong(0, 0);
                  }
                  s(t3) {
                    let e4 = this.bb.__offset(this.bb_pos, 14);
                    return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
                  }
                  t(e4) {
                    let n3 = this.bb.__offset(this.bb_pos, 16);
                    return n3 ? (e4 || new t2.experimental.fbs.Tensor()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null;
                  }
                  g(e4) {
                    let n3 = this.bb.__offset(this.bb_pos, 18);
                    return n3 ? (e4 || new t2.experimental.fbs.Graph()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null;
                  }
                  floats(t3) {
                    let e4 = this.bb.__offset(this.bb_pos, 20);
                    return e4 ? this.bb.readFloat32(this.bb.__vector(this.bb_pos + e4) + 4 * t3) : 0;
                  }
                  floatsLength() {
                    let t3 = this.bb.__offset(this.bb_pos, 20);
                    return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
                  }
                  floatsArray() {
                    let t3 = this.bb.__offset(this.bb_pos, 20);
                    return t3 ? new Float32Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + t3), this.bb.__vector_len(this.bb_pos + t3)) : null;
                  }
                  ints(t3) {
                    let e4 = this.bb.__offset(this.bb_pos, 22);
                    return e4 ? this.bb.readInt64(this.bb.__vector(this.bb_pos + e4) + 8 * t3) : this.bb.createLong(0, 0);
                  }
                  intsLength() {
                    let t3 = this.bb.__offset(this.bb_pos, 22);
                    return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
                  }
                  strings(t3, e4) {
                    let n3 = this.bb.__offset(this.bb_pos, 24);
                    return n3 ? this.bb.__string(this.bb.__vector(this.bb_pos + n3) + 4 * t3, e4) : null;
                  }
                  stringsLength() {
                    let t3 = this.bb.__offset(this.bb_pos, 24);
                    return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
                  }
                  tensors(e4, n3) {
                    let r2 = this.bb.__offset(this.bb_pos, 26);
                    return r2 ? (n3 || new t2.experimental.fbs.Tensor()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null;
                  }
                  tensorsLength() {
                    let t3 = this.bb.__offset(this.bb_pos, 26);
                    return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
                  }
                  graphs(e4, n3) {
                    let r2 = this.bb.__offset(this.bb_pos, 28);
                    return r2 ? (n3 || new t2.experimental.fbs.Graph()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null;
                  }
                  graphsLength() {
                    let t3 = this.bb.__offset(this.bb_pos, 28);
                    return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
                  }
                  static startAttribute(t3) {
                    t3.startObject(13);
                  }
                  static addName(t3, e4) {
                    t3.addFieldOffset(0, e4, 0);
                  }
                  static addDocString(t3, e4) {
                    t3.addFieldOffset(1, e4, 0);
                  }
                  static addType(e4, n3) {
                    e4.addFieldInt32(2, n3, t2.experimental.fbs.AttributeType.UNDEFINED);
                  }
                  static addF(t3, e4) {
                    t3.addFieldFloat32(3, e4, 0);
                  }
                  static addI(t3, e4) {
                    t3.addFieldInt64(4, e4, t3.createLong(0, 0));
                  }
                  static addS(t3, e4) {
                    t3.addFieldOffset(5, e4, 0);
                  }
                  static addT(t3, e4) {
                    t3.addFieldOffset(6, e4, 0);
                  }
                  static addG(t3, e4) {
                    t3.addFieldOffset(7, e4, 0);
                  }
                  static addFloats(t3, e4) {
                    t3.addFieldOffset(8, e4, 0);
                  }
                  static createFloatsVector(t3, e4) {
                    t3.startVector(4, e4.length, 4);
                    for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addFloat32(e4[n3]);
                    return t3.endVector();
                  }
                  static startFloatsVector(t3, e4) {
                    t3.startVector(4, e4, 4);
                  }
                  static addInts(t3, e4) {
                    t3.addFieldOffset(9, e4, 0);
                  }
                  static createIntsVector(t3, e4) {
                    t3.startVector(8, e4.length, 8);
                    for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addInt64(e4[n3]);
                    return t3.endVector();
                  }
                  static startIntsVector(t3, e4) {
                    t3.startVector(8, e4, 8);
                  }
                  static addStrings(t3, e4) {
                    t3.addFieldOffset(10, e4, 0);
                  }
                  static createStringsVector(t3, e4) {
                    t3.startVector(4, e4.length, 4);
                    for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addOffset(e4[n3]);
                    return t3.endVector();
                  }
                  static startStringsVector(t3, e4) {
                    t3.startVector(4, e4, 4);
                  }
                  static addTensors(t3, e4) {
                    t3.addFieldOffset(11, e4, 0);
                  }
                  static createTensorsVector(t3, e4) {
                    t3.startVector(4, e4.length, 4);
                    for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addOffset(e4[n3]);
                    return t3.endVector();
                  }
                  static startTensorsVector(t3, e4) {
                    t3.startVector(4, e4, 4);
                  }
                  static addGraphs(t3, e4) {
                    t3.addFieldOffset(12, e4, 0);
                  }
                  static createGraphsVector(t3, e4) {
                    t3.startVector(4, e4.length, 4);
                    for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addOffset(e4[n3]);
                    return t3.endVector();
                  }
                  static startGraphsVector(t3, e4) {
                    t3.startVector(4, e4, 4);
                  }
                  static endAttribute(t3) {
                    return t3.endObject();
                  }
                  static createAttribute(t3, e4, r2, i3, o2, a, s, u, c, l, p, f, d, h) {
                    return n2.startAttribute(t3), n2.addName(t3, e4), n2.addDocString(t3, r2), n2.addType(t3, i3), n2.addF(t3, o2), n2.addI(t3, a), n2.addS(t3, s), n2.addT(t3, u), n2.addG(t3, c), n2.addFloats(t3, l), n2.addInts(t3, p), n2.addStrings(t3, f), n2.addTensors(t3, d), n2.addGraphs(t3, h), n2.endAttribute(t3);
                  }
                }
                e3.Attribute = n2;
              })(e2.fbs || (e2.fbs = {}));
            })(t2.experimental || (t2.experimental = {}));
          })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) {
            !(function(e2) {
              !(function(e3) {
                class n2 {
                  constructor() {
                    this.bb = null, this.bb_pos = 0;
                  }
                  __init(t3, e4) {
                    return this.bb_pos = t3, this.bb = e4, this;
                  }
                  static getRootAsGraph(t3, e4) {
                    return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
                  }
                  static getSizePrefixedRootAsGraph(t3, e4) {
                    return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
                  }
                  initializers(e4, n3) {
                    let r2 = this.bb.__offset(this.bb_pos, 4);
                    return r2 ? (n3 || new t2.experimental.fbs.Tensor()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null;
                  }
                  initializersLength() {
                    let t3 = this.bb.__offset(this.bb_pos, 4);
                    return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
                  }
                  nodeArgs(e4, n3) {
                    let r2 = this.bb.__offset(this.bb_pos, 6);
                    return r2 ? (n3 || new t2.experimental.fbs.ValueInfo()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null;
                  }
                  nodeArgsLength() {
                    let t3 = this.bb.__offset(this.bb_pos, 6);
                    return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
                  }
                  nodes(e4, n3) {
                    let r2 = this.bb.__offset(this.bb_pos, 8);
                    return r2 ? (n3 || new t2.experimental.fbs.Node()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null;
                  }
                  nodesLength() {
                    let t3 = this.bb.__offset(this.bb_pos, 8);
                    return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
                  }
                  maxNodeIndex() {
                    let t3 = this.bb.__offset(this.bb_pos, 10);
                    return t3 ? this.bb.readUint32(this.bb_pos + t3) : 0;
                  }
                  nodeEdges(e4, n3) {
                    let r2 = this.bb.__offset(this.bb_pos, 12);
                    return r2 ? (n3 || new t2.experimental.fbs.NodeEdge()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null;
                  }
                  nodeEdgesLength() {
                    let t3 = this.bb.__offset(this.bb_pos, 12);
                    return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
                  }
                  inputs(t3, e4) {
                    let n3 = this.bb.__offset(this.bb_pos, 14);
                    return n3 ? this.bb.__string(this.bb.__vector(this.bb_pos + n3) + 4 * t3, e4) : null;
                  }
                  inputsLength() {
                    let t3 = this.bb.__offset(this.bb_pos, 14);
                    return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
                  }
                  outputs(t3, e4) {
                    let n3 = this.bb.__offset(this.bb_pos, 16);
                    return n3 ? this.bb.__string(this.bb.__vector(this.bb_pos + n3) + 4 * t3, e4) : null;
                  }
                  outputsLength() {
                    let t3 = this.bb.__offset(this.bb_pos, 16);
                    return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
                  }
                  sparseInitializers(e4, n3) {
                    let r2 = this.bb.__offset(this.bb_pos, 18);
                    return r2 ? (n3 || new t2.experimental.fbs.SparseTensor()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null;
                  }
                  sparseInitializersLength() {
                    let t3 = this.bb.__offset(this.bb_pos, 18);
                    return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
                  }
                  static startGraph(t3) {
                    t3.startObject(8);
                  }
                  static addInitializers(t3, e4) {
                    t3.addFieldOffset(0, e4, 0);
                  }
                  static createInitializersVector(t3, e4) {
                    t3.startVector(4, e4.length, 4);
                    for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addOffset(e4[n3]);
                    return t3.endVector();
                  }
                  static startInitializersVector(t3, e4) {
                    t3.startVector(4, e4, 4);
                  }
                  static addNodeArgs(t3, e4) {
                    t3.addFieldOffset(1, e4, 0);
                  }
                  static createNodeArgsVector(t3, e4) {
                    t3.startVector(4, e4.length, 4);
                    for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addOffset(e4[n3]);
                    return t3.endVector();
                  }
                  static startNodeArgsVector(t3, e4) {
                    t3.startVector(4, e4, 4);
                  }
                  static addNodes(t3, e4) {
                    t3.addFieldOffset(2, e4, 0);
                  }
                  static createNodesVector(t3, e4) {
                    t3.startVector(4, e4.length, 4);
                    for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addOffset(e4[n3]);
                    return t3.endVector();
                  }
                  static startNodesVector(t3, e4) {
                    t3.startVector(4, e4, 4);
                  }
                  static addMaxNodeIndex(t3, e4) {
                    t3.addFieldInt32(3, e4, 0);
                  }
                  static addNodeEdges(t3, e4) {
                    t3.addFieldOffset(4, e4, 0);
                  }
                  static createNodeEdgesVector(t3, e4) {
                    t3.startVector(4, e4.length, 4);
                    for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addOffset(e4[n3]);
                    return t3.endVector();
                  }
                  static startNodeEdgesVector(t3, e4) {
                    t3.startVector(4, e4, 4);
                  }
                  static addInputs(t3, e4) {
                    t3.addFieldOffset(5, e4, 0);
                  }
                  static createInputsVector(t3, e4) {
                    t3.startVector(4, e4.length, 4);
                    for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addOffset(e4[n3]);
                    return t3.endVector();
                  }
                  static startInputsVector(t3, e4) {
                    t3.startVector(4, e4, 4);
                  }
                  static addOutputs(t3, e4) {
                    t3.addFieldOffset(6, e4, 0);
                  }
                  static createOutputsVector(t3, e4) {
                    t3.startVector(4, e4.length, 4);
                    for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addOffset(e4[n3]);
                    return t3.endVector();
                  }
                  static startOutputsVector(t3, e4) {
                    t3.startVector(4, e4, 4);
                  }
                  static addSparseInitializers(t3, e4) {
                    t3.addFieldOffset(7, e4, 0);
                  }
                  static createSparseInitializersVector(t3, e4) {
                    t3.startVector(4, e4.length, 4);
                    for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addOffset(e4[n3]);
                    return t3.endVector();
                  }
                  static startSparseInitializersVector(t3, e4) {
                    t3.startVector(4, e4, 4);
                  }
                  static endGraph(t3) {
                    return t3.endObject();
                  }
                  static createGraph(t3, e4, r2, i3, o2, a, s, u, c) {
                    return n2.startGraph(t3), n2.addInitializers(t3, e4), n2.addNodeArgs(t3, r2), n2.addNodes(t3, i3), n2.addMaxNodeIndex(t3, o2), n2.addNodeEdges(t3, a), n2.addInputs(t3, s), n2.addOutputs(t3, u), n2.addSparseInitializers(t3, c), n2.endGraph(t3);
                  }
                }
                e3.Graph = n2;
              })(e2.fbs || (e2.fbs = {}));
            })(t2.experimental || (t2.experimental = {}));
          })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) {
            !(function(e2) {
              !(function(e3) {
                class n2 {
                  constructor() {
                    this.bb = null, this.bb_pos = 0;
                  }
                  __init(t3, e4) {
                    return this.bb_pos = t3, this.bb = e4, this;
                  }
                  static getRootAsModel(t3, e4) {
                    return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
                  }
                  static getSizePrefixedRootAsModel(t3, e4) {
                    return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
                  }
                  irVersion() {
                    let t3 = this.bb.__offset(this.bb_pos, 4);
                    return t3 ? this.bb.readInt64(this.bb_pos + t3) : this.bb.createLong(0, 0);
                  }
                  opsetImport(e4, n3) {
                    let r2 = this.bb.__offset(this.bb_pos, 6);
                    return r2 ? (n3 || new t2.experimental.fbs.OperatorSetId()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null;
                  }
                  opsetImportLength() {
                    let t3 = this.bb.__offset(this.bb_pos, 6);
                    return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
                  }
                  producerName(t3) {
                    let e4 = this.bb.__offset(this.bb_pos, 8);
                    return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
                  }
                  producerVersion(t3) {
                    let e4 = this.bb.__offset(this.bb_pos, 10);
                    return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
                  }
                  domain(t3) {
                    let e4 = this.bb.__offset(this.bb_pos, 12);
                    return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
                  }
                  modelVersion() {
                    let t3 = this.bb.__offset(this.bb_pos, 14);
                    return t3 ? this.bb.readInt64(this.bb_pos + t3) : this.bb.createLong(0, 0);
                  }
                  docString(t3) {
                    let e4 = this.bb.__offset(this.bb_pos, 16);
                    return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
                  }
                  graph(e4) {
                    let n3 = this.bb.__offset(this.bb_pos, 18);
                    return n3 ? (e4 || new t2.experimental.fbs.Graph()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null;
                  }
                  graphDocString(t3) {
                    let e4 = this.bb.__offset(this.bb_pos, 20);
                    return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
                  }
                  static startModel(t3) {
                    t3.startObject(9);
                  }
                  static addIrVersion(t3, e4) {
                    t3.addFieldInt64(0, e4, t3.createLong(0, 0));
                  }
                  static addOpsetImport(t3, e4) {
                    t3.addFieldOffset(1, e4, 0);
                  }
                  static createOpsetImportVector(t3, e4) {
                    t3.startVector(4, e4.length, 4);
                    for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addOffset(e4[n3]);
                    return t3.endVector();
                  }
                  static startOpsetImportVector(t3, e4) {
                    t3.startVector(4, e4, 4);
                  }
                  static addProducerName(t3, e4) {
                    t3.addFieldOffset(2, e4, 0);
                  }
                  static addProducerVersion(t3, e4) {
                    t3.addFieldOffset(3, e4, 0);
                  }
                  static addDomain(t3, e4) {
                    t3.addFieldOffset(4, e4, 0);
                  }
                  static addModelVersion(t3, e4) {
                    t3.addFieldInt64(5, e4, t3.createLong(0, 0));
                  }
                  static addDocString(t3, e4) {
                    t3.addFieldOffset(6, e4, 0);
                  }
                  static addGraph(t3, e4) {
                    t3.addFieldOffset(7, e4, 0);
                  }
                  static addGraphDocString(t3, e4) {
                    t3.addFieldOffset(8, e4, 0);
                  }
                  static endModel(t3) {
                    return t3.endObject();
                  }
                  static createModel(t3, e4, r2, i3, o2, a, s, u, c, l) {
                    return n2.startModel(t3), n2.addIrVersion(t3, e4), n2.addOpsetImport(t3, r2), n2.addProducerName(t3, i3), n2.addProducerVersion(t3, o2), n2.addDomain(t3, a), n2.addModelVersion(t3, s), n2.addDocString(t3, u), n2.addGraph(t3, c), n2.addGraphDocString(t3, l), n2.endModel(t3);
                  }
                }
                e3.Model = n2;
              })(e2.fbs || (e2.fbs = {}));
            })(t2.experimental || (t2.experimental = {}));
          })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) {
            !(function(t3) {
              !(function(t4) {
                class e2 {
                  constructor() {
                    this.bb = null, this.bb_pos = 0;
                  }
                  __init(t5, e3) {
                    return this.bb_pos = t5, this.bb = e3, this;
                  }
                  static getRootAsKernelCreateInfos(t5, n2) {
                    return (n2 || new e2()).__init(t5.readInt32(t5.position()) + t5.position(), t5);
                  }
                  static getSizePrefixedRootAsKernelCreateInfos(t5, n2) {
                    return t5.setPosition(t5.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (n2 || new e2()).__init(t5.readInt32(t5.position()) + t5.position(), t5);
                  }
                  nodeIndices(t5) {
                    let e3 = this.bb.__offset(this.bb_pos, 4);
                    return e3 ? this.bb.readUint32(this.bb.__vector(this.bb_pos + e3) + 4 * t5) : 0;
                  }
                  nodeIndicesLength() {
                    let t5 = this.bb.__offset(this.bb_pos, 4);
                    return t5 ? this.bb.__vector_len(this.bb_pos + t5) : 0;
                  }
                  nodeIndicesArray() {
                    let t5 = this.bb.__offset(this.bb_pos, 4);
                    return t5 ? new Uint32Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + t5), this.bb.__vector_len(this.bb_pos + t5)) : null;
                  }
                  kernelDefHashes(t5) {
                    let e3 = this.bb.__offset(this.bb_pos, 6);
                    return e3 ? this.bb.readUint64(this.bb.__vector(this.bb_pos + e3) + 8 * t5) : this.bb.createLong(0, 0);
                  }
                  kernelDefHashesLength() {
                    let t5 = this.bb.__offset(this.bb_pos, 6);
                    return t5 ? this.bb.__vector_len(this.bb_pos + t5) : 0;
                  }
                  static startKernelCreateInfos(t5) {
                    t5.startObject(2);
                  }
                  static addNodeIndices(t5, e3) {
                    t5.addFieldOffset(0, e3, 0);
                  }
                  static createNodeIndicesVector(t5, e3) {
                    t5.startVector(4, e3.length, 4);
                    for (let n2 = e3.length - 1; n2 >= 0; n2--) t5.addInt32(e3[n2]);
                    return t5.endVector();
                  }
                  static startNodeIndicesVector(t5, e3) {
                    t5.startVector(4, e3, 4);
                  }
                  static addKernelDefHashes(t5, e3) {
                    t5.addFieldOffset(1, e3, 0);
                  }
                  static createKernelDefHashesVector(t5, e3) {
                    t5.startVector(8, e3.length, 8);
                    for (let n2 = e3.length - 1; n2 >= 0; n2--) t5.addInt64(e3[n2]);
                    return t5.endVector();
                  }
                  static startKernelDefHashesVector(t5, e3) {
                    t5.startVector(8, e3, 8);
                  }
                  static endKernelCreateInfos(t5) {
                    return t5.endObject();
                  }
                  static createKernelCreateInfos(t5, n2, r2) {
                    return e2.startKernelCreateInfos(t5), e2.addNodeIndices(t5, n2), e2.addKernelDefHashes(t5, r2), e2.endKernelCreateInfos(t5);
                  }
                }
                t4.KernelCreateInfos = e2;
              })(t3.fbs || (t3.fbs = {}));
            })(t2.experimental || (t2.experimental = {}));
          })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) {
            !(function(e2) {
              !(function(e3) {
                class n2 {
                  constructor() {
                    this.bb = null, this.bb_pos = 0;
                  }
                  __init(t3, e4) {
                    return this.bb_pos = t3, this.bb = e4, this;
                  }
                  static getRootAsSubGraphSessionState(t3, e4) {
                    return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
                  }
                  static getSizePrefixedRootAsSubGraphSessionState(t3, e4) {
                    return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
                  }
                  graphId(t3) {
                    let e4 = this.bb.__offset(this.bb_pos, 4);
                    return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
                  }
                  sessionState(e4) {
                    let n3 = this.bb.__offset(this.bb_pos, 6);
                    return n3 ? (e4 || new t2.experimental.fbs.SessionState()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null;
                  }
                  static startSubGraphSessionState(t3) {
                    t3.startObject(2);
                  }
                  static addGraphId(t3, e4) {
                    t3.addFieldOffset(0, e4, 0);
                  }
                  static addSessionState(t3, e4) {
                    t3.addFieldOffset(1, e4, 0);
                  }
                  static endSubGraphSessionState(t3) {
                    let e4 = t3.endObject();
                    return t3.requiredField(e4, 4), e4;
                  }
                  static createSubGraphSessionState(t3, e4, r2) {
                    return n2.startSubGraphSessionState(t3), n2.addGraphId(t3, e4), n2.addSessionState(t3, r2), n2.endSubGraphSessionState(t3);
                  }
                }
                e3.SubGraphSessionState = n2;
              })(e2.fbs || (e2.fbs = {}));
            })(t2.experimental || (t2.experimental = {}));
          })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) {
            !(function(e2) {
              !(function(e3) {
                class n2 {
                  constructor() {
                    this.bb = null, this.bb_pos = 0;
                  }
                  __init(t3, e4) {
                    return this.bb_pos = t3, this.bb = e4, this;
                  }
                  static getRootAsSessionState(t3, e4) {
                    return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
                  }
                  static getSizePrefixedRootAsSessionState(t3, e4) {
                    return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
                  }
                  kernels(e4) {
                    let n3 = this.bb.__offset(this.bb_pos, 4);
                    return n3 ? (e4 || new t2.experimental.fbs.KernelCreateInfos()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null;
                  }
                  subGraphSessionStates(e4, n3) {
                    let r2 = this.bb.__offset(this.bb_pos, 6);
                    return r2 ? (n3 || new t2.experimental.fbs.SubGraphSessionState()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + r2) + 4 * e4), this.bb) : null;
                  }
                  subGraphSessionStatesLength() {
                    let t3 = this.bb.__offset(this.bb_pos, 6);
                    return t3 ? this.bb.__vector_len(this.bb_pos + t3) : 0;
                  }
                  static startSessionState(t3) {
                    t3.startObject(2);
                  }
                  static addKernels(t3, e4) {
                    t3.addFieldOffset(0, e4, 0);
                  }
                  static addSubGraphSessionStates(t3, e4) {
                    t3.addFieldOffset(1, e4, 0);
                  }
                  static createSubGraphSessionStatesVector(t3, e4) {
                    t3.startVector(4, e4.length, 4);
                    for (let n3 = e4.length - 1; n3 >= 0; n3--) t3.addOffset(e4[n3]);
                    return t3.endVector();
                  }
                  static startSubGraphSessionStatesVector(t3, e4) {
                    t3.startVector(4, e4, 4);
                  }
                  static endSessionState(t3) {
                    return t3.endObject();
                  }
                  static createSessionState(t3, e4, r2) {
                    return n2.startSessionState(t3), n2.addKernels(t3, e4), n2.addSubGraphSessionStates(t3, r2), n2.endSessionState(t3);
                  }
                }
                e3.SessionState = n2;
              })(e2.fbs || (e2.fbs = {}));
            })(t2.experimental || (t2.experimental = {}));
          })(e.onnxruntime || (e.onnxruntime = {})), (function(t2) {
            !(function(e2) {
              !(function(e3) {
                class n2 {
                  constructor() {
                    this.bb = null, this.bb_pos = 0;
                  }
                  __init(t3, e4) {
                    return this.bb_pos = t3, this.bb = e4, this;
                  }
                  static getRootAsInferenceSession(t3, e4) {
                    return (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
                  }
                  static getSizePrefixedRootAsInferenceSession(t3, e4) {
                    return t3.setPosition(t3.position() + r.flatbuffers.SIZE_PREFIX_LENGTH), (e4 || new n2()).__init(t3.readInt32(t3.position()) + t3.position(), t3);
                  }
                  static bufferHasIdentifier(t3) {
                    return t3.__has_identifier("ORTM");
                  }
                  ortVersion(t3) {
                    let e4 = this.bb.__offset(this.bb_pos, 4);
                    return e4 ? this.bb.__string(this.bb_pos + e4, t3) : null;
                  }
                  model(e4) {
                    let n3 = this.bb.__offset(this.bb_pos, 6);
                    return n3 ? (e4 || new t2.experimental.fbs.Model()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null;
                  }
                  sessionState(e4) {
                    let n3 = this.bb.__offset(this.bb_pos, 8);
                    return n3 ? (e4 || new t2.experimental.fbs.SessionState()).__init(this.bb.__indirect(this.bb_pos + n3), this.bb) : null;
                  }
                  static startInferenceSession(t3) {
                    t3.startObject(3);
                  }
                  static addOrtVersion(t3, e4) {
                    t3.addFieldOffset(0, e4, 0);
                  }
                  static addModel(t3, e4) {
                    t3.addFieldOffset(1, e4, 0);
                  }
                  static addSessionState(t3, e4) {
                    t3.addFieldOffset(2, e4, 0);
                  }
                  static endInferenceSession(t3) {
                    return t3.endObject();
                  }
                  static finishInferenceSessionBuffer(t3, e4) {
                    t3.finish(e4, "ORTM");
                  }
                  static finishSizePrefixedInferenceSessionBuffer(t3, e4) {
                    t3.finish(e4, "ORTM", true);
                  }
                  static createInferenceSession(t3, e4, r2, i3) {
                    return n2.startInferenceSession(t3), n2.addOrtVersion(t3, e4), n2.addModel(t3, r2), n2.addSessionState(t3, i3), n2.endInferenceSession(t3);
                  }
                }
                e3.InferenceSession = n2;
              })(e2.fbs || (e2.fbs = {}));
            })(t2.experimental || (t2.experimental = {}));
          })(e.onnxruntime || (e.onnxruntime = {}));
        }, 7448: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.OnnxjsSessionHandler = void 0;
          const r = n(1670), i2 = n(9162);
          e.OnnxjsSessionHandler = class {
            constructor(t2) {
              this.session = t2, this.inputNames = this.session.inputNames, this.outputNames = this.session.outputNames;
            }
            dispose() {
              return __async(this, null, function* () {
              });
            }
            run(t2, e2, n2) {
              return __async(this, null, function* () {
                const o = /* @__PURE__ */ new Map();
                for (const e3 in t2) if (Object.hasOwnProperty.call(t2, e3)) {
                  const n3 = t2[e3];
                  o.set(e3, new i2.Tensor(n3.dims, n3.type, void 0, void 0, n3.data));
                }
                const a = yield this.session.run(o), s = {};
                return a.forEach(((t3, e3) => {
                  s[e3] = new r.Tensor(t3.type, t3.data, t3.dims);
                })), s;
              });
            }
            startProfiling() {
              this.session.startProfiling();
            }
            endProfiling() {
              this.session.endProfiling();
            }
          };
        }, 6919: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.Session = void 0;
          const r = n(7067), i2 = n(1296), o = n(7091), a = n(1036), s = n(6231), u = n(2644);
          e.Session = class {
            constructor(t2 = {}) {
              this._initialized = false, this.backendHint = t2.backendHint, this.profiler = s.Profiler.create(t2.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();
            }
            loadModel(t2, e2, n2) {
              return __async(this, null, function* () {
                yield this.profiler.event("session", "Session.loadModel", (() => __async(this, null, function* () {
                  const a2 = yield (0, o.resolveBackend)(this.backendHint);
                  if (this.sessionHandler = a2.createSessionHandler(this.context), this._model = new u.Model(), "string" == typeof t2) {
                    const e3 = t2.endsWith(".ort");
                    if ("undefined" == typeof fetch) {
                      const n3 = yield (0, i2.promisify)(r.readFile)(t2);
                      this.initialize(n3, e3);
                    } else {
                      const n3 = yield fetch(t2), r2 = yield n3.arrayBuffer();
                      this.initialize(new Uint8Array(r2), e3);
                    }
                  } else if (ArrayBuffer.isView(t2)) this.initialize(t2);
                  else {
                    const r2 = new Uint8Array(t2, e2 || 0, n2 || t2.byteLength);
                    this.initialize(r2);
                  }
                })));
              });
            }
            initialize(t2, e2) {
              if (this._initialized) throw new Error("already initialized");
              this.profiler.event("session", "Session.initialize", (() => {
                const n2 = this.sessionHandler.transformGraph ? this.sessionHandler : void 0;
                this._model.load(t2, n2, e2), this.sessionHandler.onGraphInitialized && this.sessionHandler.onGraphInitialized(this._model.graph), this.initializeOps(this._model.graph), this._executionPlan = new a.ExecutionPlan(this._model.graph, this._ops, this.profiler);
              })), this._initialized = true;
            }
            run(t2) {
              return __async(this, null, function* () {
                if (!this._initialized) throw new Error("session not initialized yet");
                return this.profiler.event("session", "Session.run", (() => __async(this, null, function* () {
                  const e2 = this.normalizeAndValidateInputs(t2), n2 = yield this._executionPlan.execute(this.sessionHandler, e2);
                  return this.createOutput(n2);
                })));
              });
            }
            normalizeAndValidateInputs(t2) {
              const e2 = this._model.graph.getInputNames();
              if (Array.isArray(t2)) {
                if (t2.length !== e2.length) throw new Error(`incorrect input array length: expected ${e2.length} but got ${t2.length}`);
              } else {
                if (t2.size !== e2.length) throw new Error(`incorrect input map size: expected ${e2.length} but got ${t2.size}`);
                const n2 = new Array(t2.size);
                let r2 = 0;
                for (let i3 = 0; i3 < e2.length; ++i3) {
                  const o2 = t2.get(e2[i3]);
                  if (!o2) throw new Error(`missing input tensor for: '${name}'`);
                  n2[r2++] = o2;
                }
                t2 = n2;
              }
              if (this.context.graphInputTypes && 0 !== this.context.graphInputTypes.length && this.context.graphInputDims && 0 !== this.context.graphInputDims.length) this.validateInputTensorDims(this.context.graphInputDims, t2, false);
              else {
                const e3 = this._model.graph.getInputIndices(), n2 = this._model.graph.getValues(), r2 = new Array(e3.length);
                for (let i3 = 0; i3 < e3.length; ++i3) {
                  const o2 = n2[e3[i3]];
                  r2[i3] = o2.type.shape.dims, this.context.graphInputTypes.push(o2.type.tensorType), this.context.graphInputDims.push(t2[i3].dims);
                }
                this.validateInputTensorDims(r2, t2, true);
              }
              return this.validateInputTensorTypes(this.context.graphInputTypes, t2), t2;
            }
            validateInputTensorTypes(t2, e2) {
              for (let n2 = 0; n2 < e2.length; n2++) {
                const r2 = t2[n2], i3 = e2[n2].type;
                if (r2 !== i3) throw new Error(`input tensor[${n2}] check failed: expected type '${r2}' but got ${i3}`);
              }
            }
            validateInputTensorDims(t2, e2, n2) {
              for (let r2 = 0; r2 < e2.length; r2++) {
                const i3 = t2[r2], o2 = e2[r2].dims;
                if (!this.compareTensorDims(i3, o2, n2)) throw new Error(`input tensor[${r2}] check failed: expected shape '[${i3.join(",")}]' but got [${o2.join(",")}]`);
              }
            }
            compareTensorDims(t2, e2, n2) {
              if (t2.length !== e2.length) return false;
              for (let r2 = 0; r2 < t2.length; ++r2) if (t2[r2] !== e2[r2] && (!n2 || 0 !== t2[r2])) return false;
              return true;
            }
            createOutput(t2) {
              const e2 = this._model.graph.getOutputNames();
              if (t2.length !== e2.length) throw new Error("expected number of outputs do not match number of generated outputs");
              const n2 = /* @__PURE__ */ new Map();
              for (let r2 = 0; r2 < e2.length; ++r2) n2.set(e2[r2], t2[r2]);
              return n2;
            }
            initializeOps(t2) {
              const e2 = t2.getNodes();
              this._ops = new Array(e2.length);
              for (let n2 = 0; n2 < e2.length; n2++) this._ops[n2] = this.sessionHandler.resolve(e2[n2], this._model.opsets, t2);
            }
          };
        }, 9162: function(t, e, n) {
          var r = this && this.__importDefault || function(t2) {
            return t2 && t2.__esModule ? t2 : { default: t2 };
          };
          Object.defineProperty(e, "__esModule", { value: true }), e.Tensor = void 0;
          const i2 = n(3442), o = r(n(3720)), a = n(1446), s = n(9395), u = n(2517);
          var c = s.onnxruntime.experimental.fbs;
          class l {
            get data() {
              if (void 0 === this.cache) {
                const t2 = this.dataProvider(this.dataId);
                if (t2.length !== this.size) throw new Error("Length of data provided by the Data Provider is inconsistent with the dims of this Tensor.");
                this.cache = t2;
              }
              return this.cache;
            }
            get stringData() {
              if ("string" !== this.type) throw new TypeError("data type is not string");
              return this.data;
            }
            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 floatData() {
              switch (this.type) {
                case "float32":
                case "float64":
                  return this.data;
                default:
                  throw new TypeError("data type is not float (float32, float64)");
              }
            }
            get numberData() {
              if ("string" !== this.type) return this.data;
              throw new TypeError("type cannot be non-number (string)");
            }
            get(t2) {
              return this.data[u.ShapeUtil.indicesToOffset(t2, this.strides)];
            }
            set(t2, e2) {
              this.data[u.ShapeUtil.indicesToOffset(t2, this.strides)] = e2;
            }
            getData() {
              return __async(this, null, function* () {
                return void 0 === this.cache && (this.cache = yield this.asyncDataProvider(this.dataId)), this.cache;
              });
            }
            get strides() {
              return this._strides || (this._strides = u.ShapeUtil.computeStrides(this.dims)), this._strides;
            }
            constructor(t2, e2, n2, r2, o2, a2 = i2.Guid.create()) {
              this.dims = t2, this.type = e2, this.dataProvider = n2, this.asyncDataProvider = r2, this.cache = o2, this.dataId = a2, this.size = u.ShapeUtil.validateDimsAndCalcSize(t2);
              const s2 = this.size, c2 = void 0 === n2 && void 0 === r2 && void 0 === o2;
              if (void 0 !== o2 && o2.length !== s2) throw new RangeError("Input dims doesn't match data length.");
              if ("string" === e2) {
                if (!(void 0 === o2 || Array.isArray(o2) && o2.every(((t3) => "string" == typeof t3)))) throw new TypeError("cache should be a string array");
                c2 && (this.cache = new Array(s2));
              } else {
                if (void 0 !== o2) {
                  const t3 = f(e2);
                  if (!(o2 instanceof t3)) throw new TypeError(`cache should be type ${t3.name}`);
                }
                if (c2) {
                  const t3 = new ArrayBuffer(s2 * (function(t4) {
                    switch (t4) {
                      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 ${t4}`);
                    }
                  })(e2));
                  this.cache = (function(t4, e3) {
                    return new (f(e3))(t4);
                  })(t3, e2);
                }
              }
            }
            static fromProto(t2) {
              if (!t2) throw new Error("cannot construct Value from an empty tensor");
              const e2 = u.ProtoUtil.tensorDataTypeFromProto(t2.dataType), n2 = u.ProtoUtil.tensorDimsFromProto(t2.dims), r2 = new l(n2, e2);
              if ("string" === e2) t2.stringData.forEach(((t3, e3) => {
                r2.data[e3] = (0, u.decodeUtf8String)(t3);
              }));
              else if (t2.rawData && "number" == typeof t2.rawData.byteLength && t2.rawData.byteLength > 0) {
                const e3 = r2.data, n3 = new DataView(t2.rawData.buffer, t2.rawData.byteOffset, t2.rawData.byteLength), i3 = p(t2.dataType), o2 = t2.rawData.byteLength / i3;
                if (t2.rawData.byteLength % i3 != 0) throw new Error("invalid buffer length");
                if (e3.length !== o2) throw new Error("buffer length mismatch");
                for (let r3 = 0; r3 < o2; r3++) {
                  const o3 = h(n3, t2.dataType, r3 * i3);
                  e3[r3] = o3;
                }
              } else {
                let e3;
                switch (t2.dataType) {
                  case a.onnx.TensorProto.DataType.FLOAT:
                    e3 = t2.floatData;
                    break;
                  case a.onnx.TensorProto.DataType.INT32:
                  case a.onnx.TensorProto.DataType.INT16:
                  case a.onnx.TensorProto.DataType.UINT16:
                  case a.onnx.TensorProto.DataType.INT8:
                  case a.onnx.TensorProto.DataType.UINT8:
                  case a.onnx.TensorProto.DataType.BOOL:
                    e3 = t2.int32Data;
                    break;
                  case a.onnx.TensorProto.DataType.INT64:
                    e3 = t2.int64Data;
                    break;
                  case a.onnx.TensorProto.DataType.DOUBLE:
                    e3 = t2.doubleData;
                    break;
                  case a.onnx.TensorProto.DataType.UINT32:
                  case a.onnx.TensorProto.DataType.UINT64:
                    e3 = t2.uint64Data;
                    break;
                  default:
                    throw new Error("unspecific error");
                }
                if (null == e3) throw new Error("failed to populate data from a tensorproto value");
                const n3 = r2.data;
                if (n3.length !== e3.length) throw new Error("array length mismatch");
                for (let r3 = 0; r3 < e3.length; r3++) {
                  const i3 = e3[r3];
                  o.default.isLong(i3) ? n3[r3] = d(i3, t2.dataType) : n3[r3] = i3;
                }
              }
              return r2;
            }
            static fromData(t2, e2, n2) {
              return new l(e2, n2, void 0, void 0, t2);
            }
            static fromOrtTensor(t2) {
              if (!t2) throw new Error("cannot construct Value from an empty tensor");
              const e2 = u.ProtoUtil.tensorDimsFromORTFormat(t2), n2 = u.ProtoUtil.tensorDataTypeFromProto(t2.dataType()), r2 = new l(e2, n2);
              if ("string" === n2) for (let e3 = 0; e3 < t2.stringDataLength(); e3++) r2.data[e3] = t2.stringData(e3);
              else if (t2.rawDataArray() && "number" == typeof t2.rawDataLength() && t2.rawDataLength() > 0) {
                const e3 = r2.data, n3 = new DataView(t2.rawDataArray().buffer, t2.rawDataArray().byteOffset, t2.rawDataLength()), i3 = p(t2.dataType()), o2 = t2.rawDataLength() / i3;
                if (t2.rawDataLength() % i3 != 0) throw new Error("invalid buffer length");
                if (e3.length !== o2) throw new Error("buffer length mismatch");
                for (let r3 = 0; r3 < o2; r3++) {
                  const o3 = h(n3, t2.dataType(), r3 * i3);
                  e3[r3] = o3;
                }
              }
              return r2;
            }
          }
          function p(t2) {
            switch (t2) {
              case a.onnx.TensorProto.DataType.UINT8:
              case a.onnx.TensorProto.DataType.INT8:
              case a.onnx.TensorProto.DataType.BOOL:
                return 1;
              case a.onnx.TensorProto.DataType.UINT16:
              case a.onnx.TensorProto.DataType.INT16:
                return 2;
              case a.onnx.TensorProto.DataType.FLOAT:
              case a.onnx.TensorProto.DataType.INT32:
              case a.onnx.TensorProto.DataType.UINT32:
                return 4;
              case a.onnx.TensorProto.DataType.INT64:
              case a.onnx.TensorProto.DataType.DOUBLE:
              case a.onnx.TensorProto.DataType.UINT64:
                return 8;
              default:
                throw new Error(`cannot calculate sizeof() on type ${a.onnx.TensorProto.DataType[t2]}`);
            }
          }
          function f(t2) {
            switch (t2) {
              case "bool":
              case "uint8":
                return Uint8Array;
              case "int8":
                return Int8Array;
              case "int16":
                return Int16Array;
              case "uint16":
                return Uint16Array;
              case "int32":
                return Int32Array;
              case "uint32":
                return Uint32Array;
              case "float32":
                return Float32Array;
              case "float64":
                return Float64Array;
              default:
                throw new Error("unspecified error");
            }
          }
          function d(t2, e2) {
            if (e2 === a.onnx.TensorProto.DataType.INT64 || e2 === c.TensorDataType.INT64) {
              if (t2.greaterThanOrEqual(2147483648) || t2.lessThan(-2147483648)) throw new TypeError("int64 is not supported");
            } else {
              if (e2 !== a.onnx.TensorProto.DataType.UINT32 && e2 !== c.TensorDataType.UINT32 && e2 !== a.onnx.TensorProto.DataType.UINT64 && e2 !== c.TensorDataType.UINT64) throw new TypeError(`not a LONG type: ${a.onnx.TensorProto.DataType[e2]}`);
              if (t2.greaterThanOrEqual(4294967296) || t2.lessThan(0)) throw new TypeError("uint64 is not supported");
            }
            return t2.toNumber();
          }
          function h(t2, e2, n2) {
            switch (e2) {
              case a.onnx.TensorProto.DataType.BOOL:
              case a.onnx.TensorProto.DataType.UINT8:
                return t2.getUint8(n2);
              case a.onnx.TensorProto.DataType.INT8:
                return t2.getInt8(n2);
              case a.onnx.TensorProto.DataType.UINT16:
                return t2.getUint16(n2, true);
              case a.onnx.TensorProto.DataType.INT16:
                return t2.getInt16(n2, true);
              case a.onnx.TensorProto.DataType.FLOAT:
                return t2.getFloat32(n2, true);
              case a.onnx.TensorProto.DataType.INT32:
                return t2.getInt32(n2, true);
              case a.onnx.TensorProto.DataType.UINT32:
                return t2.getUint32(n2, true);
              case a.onnx.TensorProto.DataType.INT64:
                return d(o.default.fromBits(t2.getUint32(n2, true), t2.getUint32(n2 + 4, true), false), e2);
              case a.onnx.TensorProto.DataType.DOUBLE:
                return t2.getFloat64(n2, true);
              case a.onnx.TensorProto.DataType.UINT64:
                return d(o.default.fromBits(t2.getUint32(n2, true), t2.getUint32(n2 + 4, true), true), e2);
              default:
                throw new Error(`cannot read from DataView for type ${a.onnx.TensorProto.DataType[e2]}`);
            }
          }
          e.Tensor = l;
        }, 2517: function(t, e, n) {
          var r = this && this.__importDefault || function(t2) {
            return t2 && t2.__esModule ? t2 : { default: t2 };
          };
          Object.defineProperty(e, "__esModule", { value: true }), e.decodeUtf8String = e.MAX_CLIP = e.MIN_CLIP = e.PoolConvUtil = e.ReduceUtil = e.SplitUtil = e.MathUtil = e.ShapeUtil = e.LongUtil = e.ProtoUtil = e.GemmUtil = e.arrayCopyHelper = e.BroadcastUtil = e.MatMulUtil = e.ArrayUtil = e.assert = e.checkInputsShape = void 0;
          const i2 = n(5686), o = r(n(3720)), a = n(1446), s = n(9162);
          e.checkInputsShape = function(t2, ...e2) {
            if (!t2 || t2.length !== e2.length) return false;
            for (let n2 = 0; n2 < t2.length; n2++) if (!t2[n2].dims || t2[n2].dims.length !== e2[n2]) return false;
            return true;
          }, e.assert = function(t2, e2) {
            if (!t2) throw new Error("string" == typeof e2 ? e2 : e2());
          }, e.ArrayUtil = class {
            static arraysEqual(t2, e2) {
              if (t2.length !== e2.length) return false;
              for (let n2 = 0; n2 < t2.length; n2++) if (t2[n2] !== e2[n2]) return false;
              return true;
            }
          };
          class u {
            static preprocessInputShapes(t2, e2) {
              return [1 === t2.length ? [1, t2[0]] : t2, 1 === e2.length ? [e2[0], 1] : e2];
            }
            static postprocessOutputShape(t2, e2, n2) {
              1 === e2 && t2.splice(t2.length - 2, 1), 1 === n2 && t2.pop();
            }
            static calcMatMulShape(t2, e2) {
              return t2[1] !== e2[0] ? void 0 : [t2[0], e2[1]];
            }
          }
          e.MatMulUtil = u;
          class c {
            static calcShape(t2, e2, n2 = false) {
              const r2 = t2.length, i3 = e2.length;
              if (0 === r2) return e2;
              if (0 === i3) return t2;
              const o2 = Math.max(t2.length, e2.length), a2 = new Array(o2);
              if (n2) {
                if (r2 < 2 || i3 < 2) return;
                const n3 = u.calcMatMulShape([t2[r2 - 2], t2[r2 - 1]], [e2[i3 - 2], e2[i3 - 1]]);
                if (void 0 === n3) return;
                [a2[o2 - 2], a2[o2 - 1]] = n3;
              }
              for (let s2 = n2 ? 3 : 1; s2 <= o2; s2++) {
                const n3 = r2 - s2 < 0 ? 1 : t2[r2 - s2], u2 = i3 - s2 < 0 ? 1 : e2[i3 - s2];
                if (n3 !== u2 && n3 > 1 && u2 > 1) return;
                a2[o2 - s2] = Math.max(n3, u2);
              }
              return a2;
            }
            static index(t2, e2) {
              const n2 = new Array(e2.length);
              return c.fillIndex(t2, e2, n2), n2;
            }
            static fillIndex(t2, e2, n2) {
              const r2 = t2.length - e2.length;
              for (let i3 = 0; i3 < e2.length; i3++) n2[i3] = t2[r2 + i3] % e2[i3];
            }
            static calc(t2, e2, n2, r2, i3) {
              const o2 = c.calcShape(t2.dims, e2.dims);
              if (o2) {
                if (r2 && !f.areEqual(o2, t2.dims)) return;
                const a2 = f.size(o2), u2 = r2 ? t2 : new s.Tensor(o2, i3 || t2.type);
                if (0 === o2.length) u2.set([], n2(t2.get([]), e2.get([])));
                else {
                  const r3 = new Array(o2.length), i4 = new Array(t2.dims.length), s2 = new Array(e2.dims.length);
                  let l2, p2 = 0, f2 = 0, d2 = false, h2 = false;
                  0 === t2.dims.length && (p2 = t2.get([]), d2 = true), 0 === e2.dims.length && (f2 = e2.get([]), h2 = true);
                  for (let g2 = 0; g2 < a2; g2++) {
                    l2 = g2;
                    for (let t3 = o2.length - 1; t3 >= 0; t3--) r3[t3] = l2 % o2[t3], l2 = Math.floor(l2 / o2[t3]);
                    d2 || (c.fillIndex(r3, t2.dims, i4), p2 = t2.get(i4)), h2 || (c.fillIndex(r3, e2.dims, s2), f2 = e2.get(s2)), u2.set(r3, n2(p2, f2));
                  }
                }
                return u2;
              }
            }
            static isValidBroadcast(t2, e2) {
              const n2 = t2.length, r2 = e2.length;
              if (n2 > r2) return false;
              for (let i3 = 1; i3 <= n2; i3++) if (1 !== t2[n2 - i3] && t2[n2 - i3] !== e2[r2 - i3]) return false;
              return true;
            }
            static getBroadcastDims(t2, e2) {
              const n2 = t2.length, r2 = [];
              for (let i3 = 0; i3 < n2; i3++) {
                const o2 = n2 - 1 - i3, a2 = t2[o2] || 1;
                (e2[e2.length - 1 - i3] || 1) > 1 && 1 === a2 && r2.unshift(o2);
              }
              return r2;
            }
          }
          e.BroadcastUtil = c, e.arrayCopyHelper = function(t2, e2, n2, r2, i3) {
            if (r2 < 0 || r2 >= e2.length) throw new Error("sourceIndex out of bounds");
            if (n2 < 0 || n2 >= t2.length) throw new Error("targetIndex out of bounds");
            if (r2 + i3 > e2.length) throw new Error("source indices to be copied are outside bounds");
            if (n2 + i3 > t2.length) throw new Error("target array is too small to hold result");
            for (let o2 = 0; o2 < i3; o2++) t2[n2 + o2] = e2[r2 + o2];
          }, e.GemmUtil = class {
            static getShapeOfGemmResult(t2, e2, n2, r2, i3) {
              if (2 !== t2.length || 2 !== n2.length) throw new Error("shape need to be of size 2");
              let o2, a2, s2;
              e2 ? (o2 = t2[1], a2 = t2[0]) : (o2 = t2[0], a2 = t2[1]);
              let u2 = -1;
              if (r2 ? (s2 = n2[0], u2 = 1) : (s2 = n2[1], u2 = 0), n2[u2] !== a2) throw new Error("dimension mismatch");
              if (o2 <= 0 || s2 <= 0 || a2 <= 0) throw new Error("invalid shape specified");
              if (i3 && !c.isValidBroadcast(i3, [o2, s2])) throw new Error("gemm: invalid bias shape for broadcast");
              return [o2, s2, a2];
            }
          };
          class l {
            static tensorDataTypeFromProto(t2) {
              switch (t2) {
                case a.onnx.TensorProto.DataType.INT8:
                  return "int8";
                case a.onnx.TensorProto.DataType.UINT8:
                  return "uint8";
                case a.onnx.TensorProto.DataType.BOOL:
                  return "bool";
                case a.onnx.TensorProto.DataType.INT16:
                  return "int16";
                case a.onnx.TensorProto.DataType.UINT16:
                  return "uint16";
                case a.onnx.TensorProto.DataType.INT32:
                  return "int32";
                case a.onnx.TensorProto.DataType.UINT32:
                  return "uint32";
                case a.onnx.TensorProto.DataType.FLOAT:
                  return "float32";
                case a.onnx.TensorProto.DataType.DOUBLE:
                  return "float64";
                case a.onnx.TensorProto.DataType.STRING:
                  return "string";
                case a.onnx.TensorProto.DataType.INT64:
                  return "int32";
                case a.onnx.TensorProto.DataType.UINT64:
                  return "uint32";
                default:
                  throw new Error(`unsupported data type: ${a.onnx.TensorProto.DataType[t2]}`);
              }
            }
            static tensorDataTypeStringToEnum(t2) {
              switch (t2) {
                case "int8":
                  return a.onnx.TensorProto.DataType.INT8;
                case "uint8":
                  return a.onnx.TensorProto.DataType.UINT8;
                case "bool":
                  return a.onnx.TensorProto.DataType.BOOL;
                case "int16":
                  return a.onnx.TensorProto.DataType.INT16;
                case "uint16":
                  return a.onnx.TensorProto.DataType.UINT16;
                case "int32":
                  return a.onnx.TensorProto.DataType.INT32;
                case "uint32":
                  return a.onnx.TensorProto.DataType.UINT32;
                case "float32":
                  return a.onnx.TensorProto.DataType.FLOAT;
                case "float64":
                  return a.onnx.TensorProto.DataType.DOUBLE;
                case "string":
                  return a.onnx.TensorProto.DataType.STRING;
                case "int64":
                  return a.onnx.TensorProto.DataType.INT64;
                case "uint64":
                  return a.onnx.TensorProto.DataType.UINT64;
                default:
                  throw new Error(`unsupported data type: ${t2}`);
              }
            }
            static tensorDimsFromProto(t2) {
              return t2.map(((t3) => o.default.isLong(t3) ? t3.toNumber() : t3));
            }
            static tensorValueTypeFromProto(t2) {
              return { tensorType: l.tensorDataTypeFromProto(t2.elemType), shape: { dims: l.tensorDimsFromProto(t2.shape.dim.map(((t3) => t3.dimValue))) } };
            }
            static tensorDimsFromORTFormat(t2) {
              const e2 = [];
              for (let n2 = 0; n2 < t2.dimsLength(); n2++) e2.push(p.longToNumber(t2.dims(n2)));
              return e2;
            }
            static tensorAttributesFromORTFormat(t2) {
              const e2 = [];
              for (let n2 = 0; n2 < t2.attributesLength(); n2++) e2.push(t2.attributes(n2));
              return e2;
            }
          }
          e.ProtoUtil = l;
          class p {
            static longToNumber(t2, e2) {
              return o.default.isLong(t2) ? t2.toNumber() : t2 instanceof i2.flatbuffers.Long ? o.default.fromValue({ low: t2.low, high: t2.high, unsigned: null != e2 && e2 }).toNumber() : t2;
            }
            static isLong(t2) {
              return o.default.isLong(t2) || t2 instanceof i2.flatbuffers.Long;
            }
          }
          e.LongUtil = p;
          class f {
            static size(t2) {
              return f.getSizeFromDimensionRange(t2, 0, t2.length);
            }
            static sizeFromDimension(t2, e2) {
              if (e2 < 0 || e2 > t2.length) throw new Error(`invalid dimension of ${e2} for sizeFromDimension as Tensor has ${t2.length} dimensions.`);
              return f.getSizeFromDimensionRange(t2, e2, t2.length);
            }
            static sizeToDimension(t2, e2) {
              if (e2 < 0 || e2 > t2.length) throw new Error(`invalid dimension of ${e2} for sizeToDimension as Tensor has ${t2.length} dimensions.`);
              return f.getSizeFromDimensionRange(t2, 0, e2);
            }
            static getSizeFromDimensionRange(t2, e2, n2) {
              let r2 = 1;
              for (let i3 = e2; i3 < n2; i3++) {
                if (t2[i3] <= 0) throw new Error("cannot get valid size from specified dimension range. Most likely the range contains 0 or negative values in them.");
                r2 *= t2[i3];
              }
              return r2;
            }
            static computeStrides(t2) {
              const e2 = t2.length;
              if (0 === e2) return [];
              if (1 === e2) return [1];
              const n2 = new Array(e2);
              n2[e2 - 1] = 1, n2[e2 - 2] = t2[e2 - 1];
              for (let r2 = e2 - 3; r2 >= 0; --r2) n2[r2] = n2[r2 + 1] * t2[r2 + 1];
              return n2;
            }
            static transpose(t2) {
              return t2.slice().reverse();
            }
            static indicesToOffset(t2, e2, n2) {
              void 0 === n2 && (n2 = t2.length);
              let r2 = 0;
              for (let i3 = 0; i3 < n2; ++i3) r2 += e2[i3] * t2[i3];
              return r2;
            }
            static offsetToIndices(t2, e2) {
              const n2 = e2.length;
              if (0 === n2) return [];
              if (1 === n2) return [t2 * e2[0]];
              const r2 = new Array(e2.length);
              for (let n3 = 0; n3 < r2.length - 1; ++n3) r2[n3] = Math.floor(t2 / e2[n3]), t2 -= r2[n3] * e2[n3];
              return r2[r2.length - 1] = t2, r2;
            }
            static normalizeAxis(t2, e2) {
              if (t2 < -e2 && t2 >= e2) throw new Error("unsupported axis for this operation.");
              return t2 < 0 ? t2 + e2 : t2;
            }
            static normalizeAxes(t2, e2) {
              return t2.map(((t3) => this.normalizeAxis(t3, e2)));
            }
            static incrementIndex(t2, e2, n2) {
              if (0 === e2.length || 0 === t2.length) throw new Error("Index incrementing unsupported for scalar Tensor");
              if (void 0 === n2) n2 = e2.length;
              else if (n2 <= 0 || n2 > e2.length) throw new Error("Incorrect axis to increment on");
              for (let r2 = n2 - 1; r2 >= 0 && (t2[r2]++, !(t2[r2] < e2[r2])); --r2) t2[r2] = 0;
            }
            static calculateReshapedDims(t2, e2) {
              if (0 === e2.length) {
                if (0 === t2.length || 1 === f.size(t2)) return [];
                throw new Error("cannot reshape to a scalar Tensor");
              }
              const n2 = e2.length, r2 = new Array(n2);
              let i3 = -1, o2 = 1;
              for (let a3 = 0; a3 < n2; a3++) {
                if (e2[a3] < -1) throw new Error("a dimension in shape hints cannot be less than -1");
                if (-1 === e2[a3]) {
                  if (-1 !== i3) throw new Error("at most one dimension in shape hints can be -1");
                  i3 = a3;
                } else {
                  if (0 === e2[a3]) {
                    if (a3 >= t2.length) throw new Error("the dimension with value zero exceeds the dimension size of the input tensor");
                    r2[a3] = t2[a3];
                  } else r2[a3] = e2[a3];
                  o2 *= r2[a3];
                }
              }
              const a2 = f.size(t2);
              if (-1 !== i3) {
                if (a2 % o2 != 0) throw new Error(`the input tensor cannot be reshaped to the requested shape. Input shape: [${t2}] Output shape: [${e2}]`);
                r2[i3] = a2 / o2;
              } else if (o2 !== a2) throw new Error("reshapedDims and originalDims don't have matching sizes");
              return r2;
            }
            static sortBasedOnPerm(t2, e2) {
              return e2 ? e2.map(((e3) => t2[e3])) : t2.slice().reverse();
            }
            static padShape(t2, e2) {
              const n2 = t2.length;
              return t2.map(((t3, r2) => t3 + e2[r2] + e2[r2 + n2]));
            }
            static areEqual(t2, e2) {
              return t2.length === e2.length && t2.every(((t3, n2) => t3 === e2[n2]));
            }
            static validateDimsAndCalcSize(t2) {
              if (t2.length > 6) throw new TypeError("Only rank 0 to 6 is supported for tensor shape.");
              let e2 = 1;
              for (const n2 of t2) {
                if (!Number.isInteger(n2)) throw new TypeError(`Invalid shape: ${n2} is not an integer`);
                if (n2 < 0 || n2 > 2147483647) throw new TypeError(`Invalid shape: length ${n2} is not allowed`);
                e2 *= n2;
              }
              return e2;
            }
            static flattenShape(t2, e2) {
              e2 < 0 && (e2 += t2.length);
              const n2 = t2.reduce(((t3, e3) => t3 * e3), 1), r2 = t2.slice(e2).reduce(((t3, e3) => t3 * e3), 1);
              return [n2 / r2, r2];
            }
            static squeezeShape(t2, e2) {
              const n2 = new Array();
              e2 = f.normalizeAxes(e2, t2.length);
              for (let r2 = 0; r2 < t2.length; r2++) {
                const i3 = e2.indexOf(r2) >= 0;
                if (i3 && 1 !== t2[r2]) throw new Error("squeeze an axis of size different than 1");
                (0 === e2.length && t2[r2] > 1 || e2.length > 0 && !i3) && n2.push(t2[r2]);
              }
              return n2;
            }
            static unsqueezeShape(t2, e2) {
              const n2 = new Array(t2.length + e2.length);
              n2.fill(0);
              for (let t3 = 0; t3 < e2.length; t3++) {
                const r3 = f.normalizeAxis(e2[t3], n2.length);
                if (r3 >= n2.length) throw new Error("'axes' has an out of range axis");
                if (0 !== n2[r3]) throw new Error("'axes' has a duplicate axis");
                n2[r3] = 1;
              }
              let r2 = 0;
              for (let e3 = 0; e3 < n2.length; e3++) 0 === n2[e3] && (n2[e3] = t2[r2++]);
              if (r2 !== t2.length) throw new Error("the unsqueezed dimension could not be established");
              return n2;
            }
          }
          e.ShapeUtil = f, e.MathUtil = class {
            static sqr(t2, e2, n2, r2, i3) {
              if (r2 < 0 || r2 >= e2.length) throw new Error("sourceIndex out of bounds");
              if (n2 < 0 || n2 >= t2.length) throw new Error("targetIndex out of bounds");
              if (r2 + i3 > e2.length) throw new Error("source indices to be copied are outside bounds");
              if (n2 + i3 > t2.length) throw new Error("target array is too small to hold result");
              for (let o2 = 0; o2 < i3; o2++) t2[n2 + o2] += Math.pow(e2[r2 + o2], 2);
            }
            static axpy(t2, e2, n2, r2, i3, o2) {
              if (r2 < 0 || r2 >= e2.length) throw new Error("sourceIndex out of bounds");
              if (n2 < 0 || n2 >= t2.length) throw new Error("targetIndex out of bounds");
              if (r2 + i3 > e2.length) throw new Error("source indices to be copied are outside bounds");
              if (n2 + i3 > t2.length) throw new Error("target array is too small to hold result");
              for (let a2 = 0; a2 < i3; a2++) t2[n2 + a2] += o2 * e2[r2 + a2];
            }
            static powx(t2, e2, n2, r2, i3, o2) {
              if (r2 < 0 || r2 >= e2.length) throw new Error("sourceIndex out of bounds");
              if (n2 < 0 || n2 >= t2.length) throw new Error("targetIndex out of bounds");
              if (r2 + i3 > e2.length) throw new Error("source indices to be copied are outside bounds");
              if (n2 + i3 > t2.length) throw new Error("target array is too small to hold result");
              for (let a2 = 0; a2 < i3; a2++) t2[n2 + a2] = Math.pow(e2[r2 + a2], o2);
            }
            static mul(t2, e2, n2, r2, i3) {
              if (r2 < 0 || r2 >= e2.length) throw new Error("sourceIndex out of bounds");
              if (n2 < 0 || n2 >= t2.length) throw new Error("targetIndex out of bounds");
              if (r2 + i3 > e2.length) throw new Error("source indices to be copied are outside bounds");
              if (n2 + i3 > t2.length) throw new Error("target array is too small to hold result");
              for (let o2 = 0; o2 < i3; o2++) t2[n2 + o2] = e2[r2 + o2] * t2[n2 + o2];
            }
          };
          class d {
            static splitShape(t2, e2, n2, r2) {
              if (0 === n2.length) {
                if (!r2) throw new Error("need to know number of outputs when the 'split' attribute is not specified");
                d.determineSplit(t2[e2], r2, n2);
              }
              const i3 = [], o2 = [0];
              for (let r3 = 0; r3 < n2.length; ++r3) {
                0 !== r3 && o2.push(o2[r3 - 1] + n2[r3 - 1]);
                const a2 = t2.slice();
                a2[e2] = n2[r3], i3.push(a2);
              }
              return [i3, o2];
            }
            static determineSplit(t2, e2, n2) {
              if (t2 % e2 != 0) throw new Error("cannot split tensor to equal sized parts");
              for (let r2 = 0; r2 < e2; ++r2) n2.push(t2 / e2);
            }
          }
          e.SplitUtil = d;
          class h {
            static calcReduce(t2, e2, n2, r2, i3) {
              const o2 = t2.dims.slice(0);
              0 === e2.length && o2.forEach(((t3, n3) => e2.push(n3)));
              const a2 = h.calcReduceShape(o2, e2, true), u2 = f.size(a2), l2 = new s.Tensor(a2, t2.type), p2 = f.computeStrides(a2), d2 = f.computeStrides(o2), g2 = new Array(o2.length);
              for (let n3 = 0; n3 < u2; n3++) {
                const a3 = f.offsetToIndices(n3, p2);
                c.fillIndex(a3, o2, g2), l2.set(a3, h.calcReduceByAxis(t2.numberData, e2, o2, 0, f.indicesToOffset(g2, d2), r2, i3));
              }
              return n2 ? l2 : new s.Tensor(h.calcReduceShape(o2, e2, n2), l2.type, void 0, void 0, l2.data, l2.dataId);
            }
            static calcReduceByAxis(t2, e2, n2, r2, i3, o2, a2) {
              let s2 = 0;
              if (r2 >= e2.length) return o2(t2[i3]);
              const u2 = e2[r2], c2 = u2 >= n2.length ? 1 : f.size(n2.slice(u2 + 1));
              for (let l2 = 0; l2 < n2[u2]; l2++) s2 = 0 === l2 ? h.calcReduceByAxis(t2, e2, n2, r2 + 1, i3, o2, a2) : a2(s2, h.calcReduceByAxis(t2, e2, n2, r2 + 1, i3, o2, a2)), i3 += c2;
              return s2;
            }
            static calcReduceShape(t2, e2, n2) {
              const r2 = t2.slice();
              for (let t3 = 0; t3 < e2.length; t3++) r2[e2[t3]] = n2 ? 1 : 0;
              return r2.filter(((t3) => 0 !== t3));
            }
          }
          e.ReduceUtil = h;
          class g {
            static adjustPoolAttributes(t2, e2, n2, r2, i3, o2) {
              if (!t2 && n2.length !== e2.length - 2) throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");
              if (t2) for (let t3 = 0; t3 < e2.length - 2; t3++) t3 >= n2.length ? n2.push(e2[t3 + 2]) : n2[t3] = e2[t3 + 2];
              for (let t3 = 0; t3 < n2.length; t3++) if (t3 < r2.length) {
                if (r2[t3] < 0) throw new Error("strides should be greater than or equal to 1");
              } else r2.push(1);
              for (let t3 = 0; t3 < n2.length; t3++) if (t3 < i3.length) {
                if (i3[t3] < 0) throw new Error("dilations should be greater than or equal to 1");
              } else i3.push(1);
              for (let t3 = 0; t3 < 2 * n2.length; t3++) if (t3 < o2.length) {
                if (o2[t3] < 0) throw new Error("pad should be greater than or equal to 1");
              } else o2.push(0);
              for (let t3 = 0; t3 < n2.length; t3++) {
                if (n2[t3] <= 0) throw new Error("kernel shapes need to be greater than 0");
                if (o2[t3] >= n2[t3] || o2[t3 + n2.length] >= n2[t3]) throw new Error("pads should be smaller than kernel");
              }
            }
            static adjustPadsBasedOnAutoPad(t2, e2, n2, r2, i3, o2) {
              if (o2) {
                if (i3.length !== 2 * (t2.length - 2)) throw new Error("length of pads should be twice the length of data dimensions");
                if (e2.length !== t2.length - 2) throw new Error("length of strides should be the length of data dimensions");
                if (r2.length !== t2.length - 2) throw new Error("length of kernel shapes should be the length of data dimensions");
                for (let a2 = 0; a2 < t2.length - 2; a2++) g.adjustPadAndReturnShape(t2[a2 + 2], e2[a2], n2[a2], r2[a2], i3, a2, a2 + t2.length - 2, o2);
              }
            }
            static computePoolOutputShape(t2, e2, n2, r2, i3, o2, a2) {
              if (e2.length <= 0) throw new Error("input shape must be of size greater than 0");
              const s2 = [e2[0], e2[1]];
              return g.computeShapeHelper(t2, e2, s2, n2, r2, i3, o2, a2), s2;
            }
            static computeConvOutputShape(t2, e2, n2, r2, i3, o2, a2) {
              if (t2.length <= 0 || e2.length <= 0) throw new Error("invalid input tensor dims or invalid filter tensor dims");
              const s2 = [t2[0], e2[0]];
              return g.computeShapeHelper(false, t2, s2, n2, r2, i3, o2, a2), s2;
            }
            static computeShapeHelper(t2, e2, n2, r2, i3, o2, a2, s2) {
              if (t2) for (let t3 = 0; t3 < e2.length - 2; t3++) n2.push(1);
              else for (let t3 = 0; t3 < e2.length - 2; t3++) n2.push(g.adjustPadAndReturnShape(e2[t3 + 2], r2[t3], i3[t3], o2[t3], a2, t3, t3 + e2.length - 2, s2));
            }
            static adjustPadAndReturnShape(t2, e2, n2, r2, i3, o2, a2, s2) {
              const u2 = n2 * (r2 - 1) + 1;
              if (!s2 || "NOTSET" === s2) return Math.floor((t2 + i3[o2] + i3[a2] - u2) / e2 + 1);
              switch (s2) {
                case "VALID":
                  return i3[o2] = 0, i3[a2] = 0, Math.floor((t2 - u2) / e2 + 1);
                case "SAME_LOWER":
                case "SAME_UPPER":
                  if (1 !== n2) throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER");
                  {
                    const n3 = ((t2 + e2 - 1) / e2 - 1) * e2 + r2 - t2;
                    return i3[o2] = "SAME_LOWER" === s2 ? Math.floor((n3 + 1) / 2) : Math.floor(n3 / 2), i3[a2] = n3 - i3[o2], Math.floor((t2 + n3 - r2) / e2 + 1);
                  }
                default:
                  throw new Error("Unsupported AutoPad type");
              }
            }
          }
          e.PoolConvUtil = g, e.MIN_CLIP = -34028234663852886e22, e.MAX_CLIP = 34028234663852886e22, e.decodeUtf8String = function(t2) {
            return new TextDecoder().decode(t2);
          };
        }, 7967: (t, e) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.iterateExtraOptions = void 0, e.iterateExtraOptions = (t2, n, r, i2) => {
            if ("object" == typeof t2 && null !== t2) {
              if (r.has(t2)) throw new Error("Circular reference in options");
              r.add(t2);
            }
            Object.entries(t2).forEach((([t3, o]) => {
              const a = n ? n + t3 : t3;
              if ("object" == typeof o) (0, e.iterateExtraOptions)(o, a + ".", r, i2);
              else if ("string" == typeof o || "number" == typeof o) i2(a, o.toString());
              else {
                if ("boolean" != typeof o) throw new Error("Can't handle extra config type: " + typeof o);
                i2(a, o ? "1" : "0");
              }
            }));
          };
        }, 2157: function(t, e, n) {
          var r, i2 = this && this.__createBinding || (Object.create ? function(t2, e2, n2, r2) {
            void 0 === r2 && (r2 = n2);
            var i3 = Object.getOwnPropertyDescriptor(e2, n2);
            i3 && !("get" in i3 ? !e2.__esModule : i3.writable || i3.configurable) || (i3 = { enumerable: true, get: function() {
              return e2[n2];
            } }), Object.defineProperty(t2, r2, i3);
          } : function(t2, e2, n2, r2) {
            void 0 === r2 && (r2 = n2), t2[r2] = e2[n2];
          }), o = this && this.__setModuleDefault || (Object.create ? function(t2, e2) {
            Object.defineProperty(t2, "default", { enumerable: true, value: e2 });
          } : function(t2, e2) {
            t2.default = e2;
          }), a = this && this.__importStar || function(t2) {
            if (t2 && t2.__esModule) return t2;
            var e2 = {};
            if (null != t2) for (var n2 in t2) "default" !== n2 && Object.prototype.hasOwnProperty.call(t2, n2) && i2(e2, t2, n2);
            return o(e2, t2), e2;
          };
          Object.defineProperty(e, "__esModule", { value: true }), e.endProfiling = e.run = e.releaseSession = e.createSession = e.createSessionFinalize = e.createSessionAllocate = e.initOrt = e.initWasm = void 0;
          const s = n(1670), u = a(n(349)), c = n(6361), l = () => !!s.env.wasm.proxy && "undefined" != typeof document;
          let p, f, d, h = false, g = false, b = false;
          const m = [], y = [], _ = [], v = [], w = [], x = [], T = () => {
            if (h || !g || b || !p) throw new Error("worker not ready");
          }, S = (t2) => {
            switch (t2.data.type) {
              case "init-wasm":
                h = false, t2.data.err ? (b = true, f[1](t2.data.err)) : (g = true, f[0]());
                break;
              case "init-ort":
                t2.data.err ? d[1](t2.data.err) : d[0]();
                break;
              case "create_allocate":
                t2.data.err ? m.shift()[1](t2.data.err) : m.shift()[0](t2.data.out);
                break;
              case "create_finalize":
                t2.data.err ? y.shift()[1](t2.data.err) : y.shift()[0](t2.data.out);
                break;
              case "create":
                t2.data.err ? _.shift()[1](t2.data.err) : _.shift()[0](t2.data.out);
                break;
              case "release":
                t2.data.err ? v.shift()[1](t2.data.err) : v.shift()[0]();
                break;
              case "run":
                t2.data.err ? w.shift()[1](t2.data.err) : w.shift()[0](t2.data.out);
                break;
              case "end-profiling":
                t2.data.err ? x.shift()[1](t2.data.err) : x.shift()[0]();
            }
          }, O = "undefined" != typeof document ? null === (r = null === document || void 0 === document ? void 0 : document.currentScript) || void 0 === r ? void 0 : r.src : void 0;
          e.initWasm = () => __async(this, null, function* () {
            if (l()) {
              if (g) return;
              if (h) throw new Error("multiple calls to 'initWasm()' detected.");
              if (b) throw new Error("previous call to 'initWasm()' failed.");
              return h = true, void 0 === s.env.wasm.wasmPaths && O && 0 !== O.indexOf("blob:") && (s.env.wasm.wasmPaths = O.substr(0, +O.lastIndexOf("/") + 1)), new Promise(((t2, e2) => {
                null == p || p.terminate(), p = n(9710).Z(), p.onmessage = S, f = [t2, e2];
                const r2 = { type: "init-wasm", in: s.env.wasm };
                p.postMessage(r2);
              }));
            }
            return (0, c.initializeWebAssembly)(s.env.wasm);
          }), e.initOrt = (t2, e2) => __async(this, null, function* () {
            if (l()) return T(), new Promise(((n2, r2) => {
              d = [n2, r2];
              const i3 = { type: "init-ort", in: { numThreads: t2, loggingLevel: e2 } };
              p.postMessage(i3);
            }));
            u.initOrt(t2, e2);
          }), e.createSessionAllocate = (t2) => __async(this, null, function* () {
            return l() ? (T(), new Promise(((e2, n2) => {
              m.push([e2, n2]);
              const r2 = { type: "create_allocate", in: { model: t2 } };
              p.postMessage(r2, [t2.buffer]);
            }))) : u.createSessionAllocate(t2);
          }), e.createSessionFinalize = (t2, e2) => __async(this, null, function* () {
            return l() ? (T(), new Promise(((n2, r2) => {
              y.push([n2, r2]);
              const i3 = { type: "create_finalize", in: { modeldata: t2, options: e2 } };
              p.postMessage(i3);
            }))) : u.createSessionFinalize(t2, e2);
          }), e.createSession = (t2, e2) => __async(this, null, function* () {
            return l() ? (T(), new Promise(((n2, r2) => {
              _.push([n2, r2]);
              const i3 = { type: "create", in: { model: t2, options: e2 } };
              p.postMessage(i3, [t2.buffer]);
            }))) : u.createSession(t2, e2);
          }), e.releaseSession = (t2) => __async(this, null, function* () {
            if (l()) return T(), new Promise(((e2, n2) => {
              v.push([e2, n2]);
              const r2 = { type: "release", in: t2 };
              p.postMessage(r2);
            }));
            u.releaseSession(t2);
          }), e.run = (t2, e2, n2, r2, i3) => __async(this, null, function* () {
            return l() ? (T(), new Promise(((o2, a2) => {
              w.push([o2, a2]);
              const s2 = { type: "run", in: { sessionId: t2, inputIndices: e2, inputs: n2, outputIndices: r2, options: i3 } };
              p.postMessage(s2, u.extractTransferableBuffers(n2));
            }))) : u.run(t2, e2, n2, r2, i3);
          }), e.endProfiling = (t2) => __async(this, null, function* () {
            if (l()) return T(), new Promise(((e2, n2) => {
              x.push([e2, n2]);
              const r2 = { type: "end-profiling", in: t2 };
              p.postMessage(r2);
            }));
            u.endProfiling(t2);
          });
        }, 586: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.setRunOptions = void 0;
          const r = n(7967), i2 = n(4983), o = n(6361);
          e.setRunOptions = (t2) => {
            const e2 = (0, o.getInstance)();
            let n2 = 0;
            const a = [], s = t2 || {};
            try {
              if (void 0 === (null == t2 ? void 0 : t2.logSeverityLevel)) s.logSeverityLevel = 2;
              else if ("number" != typeof t2.logSeverityLevel || !Number.isInteger(t2.logSeverityLevel) || t2.logSeverityLevel < 0 || t2.logSeverityLevel > 4) throw new Error(`log serverity level is not valid: ${t2.logSeverityLevel}`);
              if (void 0 === (null == t2 ? void 0 : t2.logVerbosityLevel)) s.logVerbosityLevel = 0;
              else if ("number" != typeof t2.logVerbosityLevel || !Number.isInteger(t2.logVerbosityLevel)) throw new Error(`log verbosity level is not valid: ${t2.logVerbosityLevel}`);
              void 0 === (null == t2 ? void 0 : t2.terminate) && (s.terminate = false);
              let o2 = 0;
              if (void 0 !== (null == t2 ? void 0 : t2.tag) && (o2 = (0, i2.allocWasmString)(t2.tag, a)), n2 = e2._OrtCreateRunOptions(s.logSeverityLevel, s.logVerbosityLevel, !!s.terminate, o2), 0 === n2) throw new Error("Can't create run options");
              return void 0 !== (null == t2 ? void 0 : t2.extra) && (0, r.iterateExtraOptions)(t2.extra, "", /* @__PURE__ */ new WeakSet(), ((t3, r2) => {
                const o3 = (0, i2.allocWasmString)(t3, a), s2 = (0, i2.allocWasmString)(r2, a);
                if (0 !== e2._OrtAddRunConfigEntry(n2, o3, s2)) throw new Error(`Can't set a run config entry: ${t3} - ${r2}`);
              })), [n2, a];
            } catch (t3) {
              throw 0 !== n2 && e2._OrtReleaseRunOptions(n2), a.forEach(e2._free), t3;
            }
          };
        }, 2306: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.OnnxruntimeWebAssemblySessionHandler = void 0;
          const r = n(2806), i2 = n(1670), o = n(2850), a = n(2157);
          let s;
          e.OnnxruntimeWebAssemblySessionHandler = class {
            createSessionAllocate(t2) {
              return __async(this, null, function* () {
                const e2 = yield fetch(t2), n2 = yield e2.arrayBuffer();
                return (0, a.createSessionAllocate)(new Uint8Array(n2));
              });
            }
            loadModel(t2, e2) {
              return __async(this, null, function* () {
                if (s || (yield (0, a.initOrt)(i2.env.wasm.numThreads, ((t3) => {
                  switch (t3) {
                    case "verbose":
                      return 0;
                    case "info":
                      return 1;
                    case "warning":
                      return 2;
                    case "error":
                      return 3;
                    case "fatal":
                      return 4;
                    default:
                      throw new Error(`unsupported logging level: ${t3}`);
                  }
                })(i2.env.logLevel)), s = true), "string" == typeof t2) if ("undefined" == typeof fetch) {
                  const n2 = yield (0, o.promisify)(r.readFile)(t2);
                  [this.sessionId, this.inputNames, this.outputNames] = yield (0, a.createSession)(n2, e2);
                } else {
                  const n2 = yield this.createSessionAllocate(t2);
                  [this.sessionId, this.inputNames, this.outputNames] = yield (0, a.createSessionFinalize)(n2, e2);
                }
                else [this.sessionId, this.inputNames, this.outputNames] = yield (0, a.createSession)(t2, e2);
              });
            }
            dispose() {
              return __async(this, null, function* () {
                return (0, a.releaseSession)(this.sessionId);
              });
            }
            run(t2, e2, n2) {
              return __async(this, null, function* () {
                const r2 = [], o2 = [];
                Object.entries(t2).forEach(((t3) => {
                  const e3 = t3[0], n3 = t3[1], i3 = this.inputNames.indexOf(e3);
                  if (-1 === i3) throw new Error(`invalid input '${e3}'`);
                  r2.push(n3), o2.push(i3);
                }));
                const s2 = [];
                Object.entries(e2).forEach(((t3) => {
                  const e3 = t3[0], n3 = this.outputNames.indexOf(e3);
                  if (-1 === n3) throw new Error(`invalid output '${e3}'`);
                  s2.push(n3);
                }));
                const u = yield (0, a.run)(this.sessionId, o2, r2.map(((t3) => [t3.type, t3.dims, t3.data])), s2, n2), c = {};
                for (let t3 = 0; t3 < u.length; t3++) c[this.outputNames[s2[t3]]] = new i2.Tensor(u[t3][0], u[t3][2], u[t3][1]);
                return c;
              });
            }
            startProfiling() {
            }
            endProfiling() {
              (0, a.endProfiling)(this.sessionId);
            }
          };
        }, 4919: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.setSessionOptions = void 0;
          const r = n(7967), i2 = n(4983), o = n(6361);
          e.setSessionOptions = (t2) => {
            const e2 = (0, o.getInstance)();
            let n2 = 0;
            const a = [], s = t2 || {};
            ((t3) => {
              t3.extra || (t3.extra = {}), t3.extra.session || (t3.extra.session = {});
              const e3 = t3.extra.session;
              e3.use_ort_model_bytes_directly || (e3.use_ort_model_bytes_directly = "1");
            })(s);
            try {
              void 0 === (null == t2 ? void 0 : t2.graphOptimizationLevel) && (s.graphOptimizationLevel = "all");
              const u = ((t3) => {
                switch (t3) {
                  case "disabled":
                    return 0;
                  case "basic":
                    return 1;
                  case "extended":
                    return 2;
                  case "all":
                    return 99;
                  default:
                    throw new Error(`unsupported graph optimization level: ${t3}`);
                }
              })(s.graphOptimizationLevel);
              void 0 === (null == t2 ? void 0 : t2.enableCpuMemArena) && (s.enableCpuMemArena = true), void 0 === (null == t2 ? void 0 : t2.enableMemPattern) && (s.enableMemPattern = true), void 0 === (null == t2 ? void 0 : t2.executionMode) && (s.executionMode = "sequential");
              const c = ((t3) => {
                switch (t3) {
                  case "sequential":
                    return 0;
                  case "parallel":
                    return 1;
                  default:
                    throw new Error(`unsupported execution mode: ${t3}`);
                }
              })(s.executionMode);
              let l = 0;
              if (void 0 !== (null == t2 ? void 0 : t2.logId) && (l = (0, i2.allocWasmString)(t2.logId, a)), void 0 === (null == t2 ? void 0 : t2.logSeverityLevel)) s.logSeverityLevel = 2;
              else if ("number" != typeof t2.logSeverityLevel || !Number.isInteger(t2.logSeverityLevel) || t2.logSeverityLevel < 0 || t2.logSeverityLevel > 4) throw new Error(`log serverity level is not valid: ${t2.logSeverityLevel}`);
              if (void 0 === (null == t2 ? void 0 : t2.logVerbosityLevel)) s.logVerbosityLevel = 0;
              else if ("number" != typeof t2.logVerbosityLevel || !Number.isInteger(t2.logVerbosityLevel)) throw new Error(`log verbosity level is not valid: ${t2.logVerbosityLevel}`);
              if (void 0 === (null == t2 ? void 0 : t2.enableProfiling) && (s.enableProfiling = false), n2 = e2._OrtCreateSessionOptions(u, !!s.enableCpuMemArena, !!s.enableMemPattern, c, !!s.enableProfiling, 0, l, s.logSeverityLevel, s.logVerbosityLevel), 0 === n2) throw new Error("Can't create session options");
              return (null == t2 ? void 0 : t2.executionProviders) && ((t3, e3, n3) => {
                for (const r2 of e3) {
                  let e4 = "string" == typeof r2 ? r2 : r2.name;
                  switch (e4) {
                    case "xnnpack":
                      e4 = "XNNPACK";
                      break;
                    case "wasm":
                    case "cpu":
                      continue;
                    default:
                      throw new Error(`not supported EP: ${e4}`);
                  }
                  const a2 = (0, i2.allocWasmString)(e4, n3);
                  if (0 !== (0, o.getInstance)()._OrtAppendExecutionProvider(t3, a2)) throw new Error(`Can't append execution provider: ${e4}`);
                }
              })(n2, t2.executionProviders, a), void 0 !== (null == t2 ? void 0 : t2.extra) && (0, r.iterateExtraOptions)(t2.extra, "", /* @__PURE__ */ new WeakSet(), ((t3, r2) => {
                const o2 = (0, i2.allocWasmString)(t3, a), s2 = (0, i2.allocWasmString)(r2, a);
                if (0 !== e2._OrtAddSessionConfigEntry(n2, o2, s2)) throw new Error(`Can't set a session config entry: ${t3} - ${r2}`);
              })), [n2, a];
            } catch (t3) {
              throw 0 !== n2 && e2._OrtReleaseSessionOptions(n2), a.forEach(e2._free), t3;
            }
          };
        }, 4983: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.allocWasmString = void 0;
          const r = n(6361);
          e.allocWasmString = (t2, e2) => {
            const n2 = (0, r.getInstance)(), i2 = n2.lengthBytesUTF8(t2) + 1, o = n2._malloc(i2);
            return n2.stringToUTF8(t2, o, i2), e2.push(o), o;
          };
        }, 349: (t, e, n) => {
          Object.defineProperty(e, "__esModule", { value: true }), e.extractTransferableBuffers = e.endProfiling = e.run = e.releaseSession = e.createSession = e.createSessionFinalize = e.createSessionAllocate = e.initOrt = void 0;
          const r = n(586), i2 = n(4919), o = n(4983), a = n(6361);
          e.initOrt = (t2, e2) => {
            const n2 = (0, a.getInstance)()._OrtInit(t2, e2);
            if (0 !== n2) throw new Error(`Can't initialize onnxruntime. error code = ${n2}`);
          };
          const s = /* @__PURE__ */ new Map();
          e.createSessionAllocate = (t2) => {
            const e2 = (0, a.getInstance)(), n2 = e2._malloc(t2.byteLength);
            return e2.HEAPU8.set(t2, n2), [n2, t2.byteLength];
          }, e.createSessionFinalize = (t2, e2) => {
            const n2 = (0, a.getInstance)();
            let r2 = 0, o2 = 0, u2 = [];
            try {
              if ([o2, u2] = (0, i2.setSessionOptions)(e2), r2 = n2._OrtCreateSession(t2[0], t2[1], o2), 0 === r2) throw new Error("Can't create a session");
            } finally {
              n2._free(t2[0]), n2._OrtReleaseSessionOptions(o2), u2.forEach(n2._free);
            }
            const c2 = n2._OrtGetInputCount(r2), l2 = n2._OrtGetOutputCount(r2), p = [], f = [], d = [], h = [];
            for (let t3 = 0; t3 < c2; t3++) {
              const e3 = n2._OrtGetInputName(r2, t3);
              if (0 === e3) throw new Error("Can't get an input name");
              f.push(e3), p.push(n2.UTF8ToString(e3));
            }
            for (let t3 = 0; t3 < l2; t3++) {
              const e3 = n2._OrtGetOutputName(r2, t3);
              if (0 === e3) throw new Error("Can't get an output name");
              h.push(e3), d.push(n2.UTF8ToString(e3));
            }
            return s.set(r2, [r2, f, h]), [r2, p, d];
          }, e.createSession = (t2, n2) => {
            const r2 = (0, e.createSessionAllocate)(t2);
            return (0, e.createSessionFinalize)(r2, n2);
          }, e.releaseSession = (t2) => {
            const e2 = (0, a.getInstance)(), n2 = s.get(t2);
            if (!n2) throw new Error("invalid session id");
            const r2 = n2[0], i3 = n2[1], o2 = n2[2];
            i3.forEach(e2._OrtFree), o2.forEach(e2._OrtFree), e2._OrtReleaseSession(r2), s.delete(t2);
          };
          const u = (t2) => {
            switch (t2) {
              case "int8":
                return 3;
              case "uint8":
                return 2;
              case "bool":
                return 9;
              case "int16":
                return 5;
              case "uint16":
                return 4;
              case "int32":
                return 6;
              case "uint32":
                return 12;
              case "float32":
                return 1;
              case "float64":
                return 11;
              case "string":
                return 8;
              case "int64":
                return 7;
              case "uint64":
                return 13;
              default:
                throw new Error(`unsupported data type: ${t2}`);
            }
          }, c = (t2) => {
            switch (t2) {
              case 3:
                return "int8";
              case 2:
                return "uint8";
              case 9:
                return "bool";
              case 5:
                return "int16";
              case 4:
                return "uint16";
              case 6:
                return "int32";
              case 12:
                return "uint32";
              case 1:
                return "float32";
              case 11:
                return "float64";
              case 8:
                return "string";
              case 7:
                return "int64";
              case 13:
                return "uint64";
              default:
                throw new Error(`unsupported data type: ${t2}`);
            }
          }, l = (t2) => {
            switch (t2) {
              case "float32":
                return Float32Array;
              case "uint8":
              case "bool":
                return Uint8Array;
              case "int8":
                return Int8Array;
              case "uint16":
                return Uint16Array;
              case "int16":
                return Int16Array;
              case "int32":
                return Int32Array;
              case "float64":
                return Float64Array;
              case "uint32":
                return Uint32Array;
              case "int64":
                return BigInt64Array;
              case "uint64":
                return BigUint64Array;
              default:
                throw new Error(`unsupported type: ${t2}`);
            }
          };
          e.run = (t2, e2, n2, i3, p) => {
            const f = (0, a.getInstance)(), d = s.get(t2);
            if (!d) throw new Error("invalid session id");
            const h = d[0], g = d[1], b = d[2], m = e2.length, y = i3.length;
            let _ = 0, v = [];
            const w = [], x = [];
            try {
              [_, v] = (0, r.setRunOptions)(p);
              for (let t4 = 0; t4 < m; t4++) {
                const e3 = n2[t4][0], r2 = n2[t4][1], i4 = n2[t4][2];
                let a3, s3;
                if (Array.isArray(i4)) {
                  s3 = 4 * i4.length, a3 = f._malloc(s3), x.push(a3);
                  let t5 = a3 / 4;
                  for (let e4 = 0; e4 < i4.length; e4++) {
                    if ("string" != typeof i4[e4]) throw new TypeError(`tensor data at index ${e4} is not a string`);
                    f.HEAPU32[t5++] = (0, o.allocWasmString)(i4[e4], x);
                  }
                } else s3 = i4.byteLength, a3 = f._malloc(s3), x.push(a3), f.HEAPU8.set(new Uint8Array(i4.buffer, i4.byteOffset, s3), a3);
                const c2 = f.stackSave(), l2 = f.stackAlloc(4 * r2.length);
                try {
                  let t5 = l2 / 4;
                  r2.forEach(((e4) => f.HEAP32[t5++] = e4));
                  const n3 = f._OrtCreateTensor(u(e3), a3, s3, l2, r2.length);
                  if (0 === n3) throw new Error("Can't create a tensor");
                  w.push(n3);
                } finally {
                  f.stackRestore(c2);
                }
              }
              const t3 = f.stackSave(), a2 = f.stackAlloc(4 * m), s2 = f.stackAlloc(4 * m), d2 = f.stackAlloc(4 * y), T = f.stackAlloc(4 * y);
              try {
                let n3 = a2 / 4, r2 = s2 / 4, o2 = d2 / 4, u2 = T / 4;
                for (let t4 = 0; t4 < m; t4++) f.HEAPU32[n3++] = w[t4], f.HEAPU32[r2++] = g[e2[t4]];
                for (let t4 = 0; t4 < y; t4++) f.HEAPU32[o2++] = 0, f.HEAPU32[u2++] = b[i3[t4]];
                let p2 = f._OrtRun(h, s2, a2, m, T, y, d2, _);
                const v2 = [];
                if (0 === p2) for (let t4 = 0; t4 < y; t4++) {
                  const e3 = f.HEAPU32[d2 / 4 + t4], n4 = f.stackSave(), r3 = f.stackAlloc(16);
                  let i4, o3 = 0;
                  try {
                    if (p2 = f._OrtGetTensorData(e3, r3, r3 + 4, r3 + 8, r3 + 12), 0 !== p2) throw new Error(`Can't access output tensor data. error code = ${p2}`);
                    let t5 = r3 / 4;
                    const a3 = f.HEAPU32[t5++];
                    o3 = f.HEAPU32[t5++];
                    const s3 = f.HEAPU32[t5++], u3 = f.HEAPU32[t5++], d3 = [];
                    for (let t6 = 0; t6 < u3; t6++) d3.push(f.HEAPU32[s3 / 4 + t6]);
                    f._OrtFree(s3);
                    const h2 = 0 === d3.length ? 1 : d3.reduce(((t6, e4) => t6 * e4));
                    if (i4 = c(a3), "string" === i4) {
                      const t6 = [];
                      let e4 = o3 / 4;
                      for (let n5 = 0; n5 < h2; n5++) {
                        const r4 = f.HEAPU32[e4++], i5 = n5 === h2 - 1 ? void 0 : f.HEAPU32[e4] - r4;
                        t6.push(f.UTF8ToString(r4, i5));
                      }
                      v2.push([i4, d3, t6]);
                    } else {
                      const t6 = new (l(i4))(h2);
                      new Uint8Array(t6.buffer, t6.byteOffset, t6.byteLength).set(f.HEAPU8.subarray(o3, o3 + t6.byteLength)), v2.push([i4, d3, t6]);
                    }
                  } finally {
                    f.stackRestore(n4), "string" === i4 && o3 && f._free(o3), f._OrtReleaseTensor(e3);
                  }
                }
                if (0 === p2) return v2;
                throw new Error(`failed to call OrtRun(). error code = ${p2}.`);
              } finally {
                f.stackRestore(t3);
              }
            } finally {
              w.forEach(f._OrtReleaseTensor), x.forEach(f._free), f._OrtReleaseRunOptions(_), v.forEach(f._free);
            }
          }, e.endProfiling = (t2) => {
            const e2 = (0, a.getInstance)(), n2 = s.get(t2);
            if (!n2) throw new Error("invalid session id");
            const r2 = n2[0], i3 = e2._OrtEndProfiling(r2);
            if (0 === i3) throw new Error("Can't get an profile file name");
            e2._OrtFree(i3);
          }, e.extractTransferableBuffers = (t2) => {
            const e2 = [];
            for (const n2 of t2) {
              const t3 = n2[2];
              !Array.isArray(t3) && t3.buffer && e2.push(t3.buffer);
            }
            return e2;
          };
        }, 6361: function(t, e, n) {
          var r = this && this.__createBinding || (Object.create ? function(t2, e2, n2, r2) {
            void 0 === r2 && (r2 = n2);
            var i3 = Object.getOwnPropertyDescriptor(e2, n2);
            i3 && !("get" in i3 ? !e2.__esModule : i3.writable || i3.configurable) || (i3 = { enumerable: true, get: function() {
              return e2[n2];
            } }), Object.defineProperty(t2, r2, i3);
          } : function(t2, e2, n2, r2) {
            void 0 === r2 && (r2 = n2), t2[r2] = e2[n2];
          }), i2 = this && this.__setModuleDefault || (Object.create ? function(t2, e2) {
            Object.defineProperty(t2, "default", { enumerable: true, value: e2 });
          } : function(t2, e2) {
            t2.default = e2;
          }), o = this && this.__importStar || function(t2) {
            if (t2 && t2.__esModule) return t2;
            var e2 = {};
            if (null != t2) for (var n2 in t2) "default" !== n2 && Object.prototype.hasOwnProperty.call(t2, n2) && r(e2, t2, n2);
            return i2(e2, t2), e2;
          }, a = this && this.__importDefault || function(t2) {
            return t2 && t2.__esModule ? t2 : { default: t2 };
          };
          Object.defineProperty(e, "__esModule", { value: true }), e.dispose = e.getInstance = e.initializeWebAssembly = void 0;
          const s = o(n(6449)), u = a(n(932)), c = n(3474);
          let l, p = false, f = false, d = false;
          const h = (t2, e2) => e2 ? t2 ? "ort-wasm-simd-threaded.wasm" : "ort-wasm-threaded.wasm" : t2 ? "ort-wasm-simd.wasm" : "ort-wasm.wasm";
          e.initializeWebAssembly = (t2) => __async(this, null, function* () {
            if (p) return Promise.resolve();
            if (f) throw new Error("multiple calls to 'initializeWebAssembly()' detected.");
            if (d) throw new Error("previous call to 'initializeWebAssembly()' failed.");
            f = true;
            const e2 = t2.initTimeout, r2 = t2.numThreads, i3 = t2.simd, o2 = r2 > 1 && (() => {
              try {
                return "undefined" != typeof SharedArrayBuffer && ("undefined" != typeof MessageChannel && new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)), WebAssembly.validate(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 5, 4, 1, 3, 1, 1, 10, 11, 1, 9, 0, 65, 0, 254, 16, 2, 0, 26, 11])));
              } catch (t3) {
                return false;
              }
            })(), a2 = i3 && (() => {
              try {
                return WebAssembly.validate(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 30, 1, 28, 0, 65, 0, 253, 15, 253, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 253, 186, 1, 26, 11]));
              } catch (t3) {
                return false;
              }
            })(), g = "string" == typeof t2.wasmPaths ? t2.wasmPaths : void 0, b = h(false, o2), m = h(a2, o2), y = "object" == typeof t2.wasmPaths ? t2.wasmPaths[m] : void 0;
            let _ = false;
            const v = [];
            if (e2 > 0 && v.push(new Promise(((t3) => {
              setTimeout((() => {
                _ = true, t3();
              }), e2);
            }))), v.push(new Promise(((t3, e3) => {
              const r3 = o2 ? c : u.default, i4 = { locateFile: (t4, e4) => o2 && t4.endsWith(".worker.js") && "undefined" != typeof Blob ? URL.createObjectURL(new Blob([n(4154)], { type: "text/javascript" })) : t4 === b ? null != y ? y : (null != g ? g : e4) + m : e4 + t4 };
              if (o2) if ("undefined" == typeof Blob) i4.mainScriptUrlOrBlob = s.join("/", "ort-wasm-threaded.js");
              else {
                const t4 = `var ortWasmThreaded=(function(){var _scriptDir;return ${r3.toString()}})();`;
                i4.mainScriptUrlOrBlob = new Blob([t4], { type: "text/javascript" });
              }
              r3(i4).then(((e4) => {
                f = false, p = true, l = e4, t3();
              }), ((t4) => {
                f = false, d = true, e3(t4);
              }));
            }))), yield Promise.race(v), _) throw new Error(`WebAssembly backend initializing failed due to timeout: ${e2}ms`);
          }), e.getInstance = () => {
            if (p && l) return l;
            throw new Error("WebAssembly is not initialized yet.");
          }, e.dispose = () => {
            var t2;
            !p || f || d || (f = true, null === (t2 = l.PThread) || void 0 === t2 || t2.terminateAllThreads(), l = void 0, f = false, p = false, d = true);
          };
        }, 9710: (t, e, n) => {
          n.d(e, { Z: () => o });
          var r = n(477), i2 = n.n(r);
          function o() {
            return i2()('/*!\n* ONNX Runtime Web v1.14.0\n* Copyright (c) Microsoft Corporation. All rights reserved.\n* Licensed under the MIT License.\n*/\n(()=>{var t={474:(t,e,n)=>{var _scriptDir,r=(_scriptDir=(_scriptDir="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(t){function e(){return j.buffer!=D&&N(j.buffer),P}function r(){return j.buffer!=D&&N(j.buffer),U}function a(){return j.buffer!=D&&N(j.buffer),F}function i(){return j.buffer!=D&&N(j.buffer),I}function o(){return j.buffer!=D&&N(j.buffer),W}var u,c,s;t=t||{},u||(u=void 0!==t?t:{}),u.ready=new Promise((function(t,e){c=t,s=e}));var l,f,p,h,d,y,b=Object.assign({},u),m="./this.program",g=(t,e)=>{throw e},v="object"==typeof window,w="function"==typeof importScripts,_="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,O=u.ENVIRONMENT_IS_PTHREAD||!1,A="";function S(t){return u.locateFile?u.locateFile(t,A):A+t}if(_){let e;A=w?n(908).dirname(A)+"/":"//",y=()=>{d||(h=n(384),d=n(908))},l=function(t,e){return y(),t=d.normalize(t),h.readFileSync(t,e?void 0:"utf8")},p=t=>((t=l(t,!0)).buffer||(t=new Uint8Array(t)),t),f=(t,e,n)=>{y(),t=d.normalize(t),h.readFile(t,(function(t,r){t?n(t):e(r.buffer)}))},1<process.argv.length&&(m=process.argv[1].replace(/\\\\/g,"/")),process.argv.slice(2),process.on("uncaughtException",(function(t){if(!(t instanceof ct))throw t})),process.on("unhandledRejection",(function(t){throw t})),g=(t,e)=>{if(Q())throw process.exitCode=t,e;e instanceof ct||x("exiting due to exception: "+e),process.exit(t)},u.inspect=function(){return"[Emscripten Module object]"};try{e=n(925)}catch(t){throw console.error(\'The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?\'),t}n.g.Worker=e.Worker}else(v||w)&&(w?A=self.location.href:"undefined"!=typeof document&&document.currentScript&&(A=document.currentScript.src),_scriptDir&&(A=_scriptDir),A=0!==A.indexOf("blob:")?A.substr(0,A.replace(/[?#].*/,"").lastIndexOf("/")+1):"",_||(l=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.send(null),e.responseText},w&&(p=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),f=(t,e,n)=>{var r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?e(r.response):n()},r.onerror=n,r.send(null)}));_&&"undefined"==typeof performance&&(n.g.performance=n(953).performance);var T=console.log.bind(console),E=console.warn.bind(console);_&&(y(),T=t=>h.writeSync(1,t+"\\n"),E=t=>h.writeSync(2,t+"\\n"));var M,C=u.print||T,x=u.printErr||E;Object.assign(u,b),b=null,u.thisProgram&&(m=u.thisProgram),u.quit&&(g=u.quit),u.wasmBinary&&(M=u.wasmBinary);var R=u.noExitRuntime||!1;"object"!=typeof WebAssembly&&at("no native wasm support detected");var j,k,D,P,U,F,I,W,H=!1,L="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function z(t,e,n){var r=(e>>>=0)+n;for(n=e;t[n]&&!(n>=r);)++n;if(16<n-e&&t.buffer&&L)return L.decode(t.buffer instanceof SharedArrayBuffer?t.slice(e,n):t.subarray(e,n));for(r="";e<n;){var a=t[e++];if(128&a){var i=63&t[e++];if(192==(224&a))r+=String.fromCharCode((31&a)<<6|i);else{var o=63&t[e++];65536>(a=224==(240&a)?(15&a)<<12|i<<6|o:(7&a)<<18|i<<12|o<<6|63&t[e++])?r+=String.fromCharCode(a):(a-=65536,r+=String.fromCharCode(55296|a>>10,56320|1023&a))}}else r+=String.fromCharCode(a)}return r}function Y(t,e){return(t>>>=0)?z(r(),t,e):""}function B(t,e,n,r){if(!(0<r))return 0;var a=n>>>=0;r=n+r-1;for(var i=0;i<t.length;++i){var o=t.charCodeAt(i);if(55296<=o&&57343>=o&&(o=65536+((1023&o)<<10)|1023&t.charCodeAt(++i)),127>=o){if(n>=r)break;e[n++>>>0]=o}else{if(2047>=o){if(n+1>=r)break;e[n++>>>0]=192|o>>6}else{if(65535>=o){if(n+2>=r)break;e[n++>>>0]=224|o>>12}else{if(n+3>=r)break;e[n++>>>0]=240|o>>18,e[n++>>>0]=128|o>>12&63}e[n++>>>0]=128|o>>6&63}e[n++>>>0]=128|63&o}}return e[n>>>0]=0,n-a}function G(t){for(var e=0,n=0;n<t.length;++n){var r=t.charCodeAt(n);127>=r?e++:2047>=r?e+=2:55296<=r&&57343>=r?(e+=4,++n):e+=3}return e}function N(t){D=t,u.HEAP8=P=new Int8Array(t),u.HEAP16=new Int16Array(t),u.HEAP32=F=new Int32Array(t),u.HEAPU8=U=new Uint8Array(t),u.HEAPU16=new Uint16Array(t),u.HEAPU32=I=new Uint32Array(t),u.HEAPF32=new Float32Array(t),u.HEAPF64=W=new Float64Array(t)}O&&(D=u.buffer);var V=u.INITIAL_MEMORY||16777216;if(O)j=u.wasmMemory,D=u.buffer;else if(u.wasmMemory)j=u.wasmMemory;else if(!((j=new WebAssembly.Memory({initial:V/65536,maximum:65536,shared:!0})).buffer instanceof SharedArrayBuffer))throw x("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),_&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");j&&(D=j.buffer),V=D.byteLength,N(D);var $,q=[],X=[],J=[],Z=[];function Q(){return R||!1}function K(){var t=u.preRun.shift();q.unshift(t)}var tt,et=0,nt=null,rt=null;function at(t){throw O?postMessage({cmd:"onAbort",arg:t}):u.onAbort&&u.onAbort(t),x(t="Aborted("+t+")"),H=!0,t=new WebAssembly.RuntimeError(t+". Build with -sASSERTIONS for more info."),s(t),t}function it(){return tt.startsWith("data:application/octet-stream;base64,")}function ot(){var t=tt;try{if(t==tt&&M)return new Uint8Array(M);if(p)return p(t);throw"both async and sync fetching of the wasm failed"}catch(t){at(t)}}tt="ort-wasm-threaded.wasm",it()||(tt=S(tt));var ut={};function ct(t){this.name="ExitStatus",this.message="Program terminated with exit("+t+")",this.status=t}function st(t){(t=ht.Vb[t])||at(),ht.mc(t)}function lt(t){var e=ht.Cc();if(!e)return 6;ht.ac.push(e),ht.Vb[t.Ub]=e,e.Ub=t.Ub;var n={cmd:"run",start_routine:t.Ic,arg:t.zc,pthread_ptr:t.Ub};return e.$b=()=>{n.time=performance.now(),e.postMessage(n,t.Nc)},e.loaded&&(e.$b(),delete e.$b),0}function ft(t){if(O)return $t(1,1,t);Q()||(ht.oc(),u.onExit&&u.onExit(t),H=!0),g(t,new ct(t))}function pt(t,e){if(!e&&O)throw bt(t),"unwind";Q()||O||(me(),dt(J),be(0),re[1].length&&ae(1,10),re[2].length&&ae(2,10),ht.oc()),ft(t)}var ht={Yb:[],ac:[],qc:[],Vb:{},fc:function(){O&&ht.Ec()},Pc:function(){},Ec:function(){ht.receiveObjectTransfer=ht.Gc,ht.threadInitTLS=ht.pc,ht.setExitStatus=ht.nc,R=!1},nc:function(){},oc:function(){for(var t of Object.values(ht.Vb))ht.mc(t);for(t of ht.Yb)t.terminate();ht.Yb=[]},mc:function(t){var e=t.Ub;delete ht.Vb[e],ht.Yb.push(t),ht.ac.splice(ht.ac.indexOf(t),1),t.Ub=0,Oe(e)},Gc:function(){},pc:function(){ht.qc.forEach((t=>t()))},Fc:function(t,e){t.onmessage=n=>{var r=(n=n.data).cmd;if(t.Ub&&(ht.Bc=t.Ub),n.targetThread&&n.targetThread!=he()){var a=ht.Vb[n.Qc];a?a.postMessage(n,n.transferList):x(\'Internal error! Worker sent a message "\'+r+\'" to target pthread \'+n.targetThread+", but that thread no longer exists!")}else"processProxyingQueue"===r?zt(n.queue):"spawnThread"===r?lt(n):"cleanupThread"===r?st(n.thread):"killThread"===r?(n=n.thread,r=ht.Vb[n],delete ht.Vb[n],r.terminate(),Oe(n),ht.ac.splice(ht.ac.indexOf(r),1),r.Ub=0):"cancelThread"===r?ht.Vb[n.thread].postMessage({cmd:"cancel"}):"loaded"===r?(t.loaded=!0,e&&e(t),t.$b&&(t.$b(),delete t.$b)):"print"===r?C("Thread "+n.threadId+": "+n.text):"printErr"===r?x("Thread "+n.threadId+": "+n.text):"alert"===r?alert("Thread "+n.threadId+": "+n.text):"setimmediate"===n.target?t.postMessage(n):"onAbort"===r?u.onAbort&&u.onAbort(n.arg):r&&x("worker sent an unknown command "+r);ht.Bc=void 0},t.onerror=t=>{throw x("worker sent an error! "+t.filename+":"+t.lineno+": "+t.message),t},_&&(t.on("message",(function(e){t.onmessage({data:e})})),t.on("error",(function(e){t.onerror(e)})),t.on("detachedExit",(function(){}))),t.postMessage({cmd:"load",urlOrBlob:u.mainScriptUrlOrBlob||_scriptDir,wasmMemory:j,wasmModule:k})},yc:function(){var t=S("ort-wasm-threaded.worker.js");ht.Yb.push(new Worker(t))},Cc:function(){return 0==ht.Yb.length&&(ht.yc(),ht.Fc(ht.Yb[0])),ht.Yb.pop()}};function dt(t){for(;0<t.length;)t.shift()(u)}function yt(t){var e=Ee();return t=t(),Me(e),t}function bt(t){if(O)return $t(2,0,t);try{pt(t)}catch(t){t instanceof ct||"unwind"==t||g(1,t)}}u.PThread=ht,u.establishStackSpace=function(){var t=he(),e=a()[t+44>>2>>>0];t=a()[t+48>>2>>>0],Te(e,e-t),Me(e)};var mt=[];function gt(t){var e=mt[t];return e||(t>=mt.length&&(mt.length=t+1),mt[t]=e=$.get(t)),e}u.invokeEntryPoint=function(t,e){t=gt(t)(e),Q()?ht.nc(t):Ae(t)};var vt,wt,_t=[],Ot=0,At=0;function St(t){this.Zb=t,this.Sb=t-24,this.xc=function(t){i()[this.Sb+4>>2>>>0]=t},this.bc=function(){return i()[this.Sb+4>>2>>>0]},this.wc=function(t){i()[this.Sb+8>>2>>>0]=t},this.Dc=function(){return i()[this.Sb+8>>2>>>0]},this.rc=function(){a()[this.Sb>>2>>>0]=0},this.hc=function(t){t=t?1:0,e()[this.Sb+12>>0>>>0]=t},this.uc=function(){return 0!=e()[this.Sb+12>>0>>>0]},this.ic=function(t){t=t?1:0,e()[this.Sb+13>>0>>>0]=t},this.kc=function(){return 0!=e()[this.Sb+13>>0>>>0]},this.fc=function(t,e){this.cc(0),this.xc(t),this.wc(e),this.rc(),this.hc(!1),this.ic(!1)},this.sc=function(){Atomics.add(a(),this.Sb>>2,1)},this.Hc=function(){return 1===Atomics.sub(a(),this.Sb>>2,1)},this.cc=function(t){i()[this.Sb+16>>2>>>0]=t},this.tc=function(){return i()[this.Sb+16>>2>>>0]},this.vc=function(){if(Re(this.bc()))return i()[this.Zb>>2>>>0];var t=this.tc();return 0!==t?t:this.Zb}}function Tt(t){return ye(new St(t).Sb)}function Et(t,e,n,r){return O?$t(3,1,t,e,n,r):Mt(t,e,n,r)}function Mt(t,e,n,r){if("undefined"==typeof SharedArrayBuffer)return x("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var a=[];return O&&0===a.length?Et(t,e,n,r):(t={Ic:n,Ub:t,zc:r,Nc:a},O?(t.Oc="spawnThread",postMessage(t,a),0):lt(t))}function Ct(t,e,n){return O?$t(4,1,t,e,n):0}function xt(t,e){if(O)return $t(5,1,t,e)}function Rt(t,e){if(O)return $t(6,1,t,e)}function jt(t,e,n){if(O)return $t(7,1,t,e,n)}function kt(t,e,n){return O?$t(8,1,t,e,n):0}function Dt(t,e){if(O)return $t(9,1,t,e)}function Pt(t,e,n){if(O)return $t(10,1,t,e,n)}function Ut(t,e,n,r){if(O)return $t(11,1,t,e,n,r)}function Ft(t,e,n,r){if(O)return $t(12,1,t,e,n,r)}function It(t,e,n,r){if(O)return $t(13,1,t,e,n,r)}function Wt(t){if(O)return $t(14,1,t)}function Ht(t,e){if(O)return $t(15,1,t,e)}function Lt(t,e,n){if(O)return $t(16,1,t,e,n)}function zt(t){Atomics.store(a(),t>>2,1),he()&&_e(t),Atomics.compareExchange(a(),t>>2,1,0)}function Yt(t){return i()[t>>>2]+4294967296*a()[t+4>>>2]}function Bt(t,e,n,r,a,i){return O?$t(17,1,t,e,n,r,a,i):-52}function Gt(t,e,n,r,a,i){if(O)return $t(18,1,t,e,n,r,a,i)}function Nt(t){var n=G(t)+1,r=de(n);return r&&B(t,e(),r,n),r}function Vt(t,e,n){function r(t){return(t=t.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?t[1]:"GMT"}if(O)return $t(19,1,t,e,n);var o=(new Date).getFullYear(),u=new Date(o,0,1),c=new Date(o,6,1);o=u.getTimezoneOffset();var s=c.getTimezoneOffset(),l=Math.max(o,s);a()[t>>2>>>0]=60*l,a()[e>>2>>>0]=Number(o!=s),t=r(u),e=r(c),t=Nt(t),e=Nt(e),s<o?(i()[n>>2>>>0]=t,i()[n+4>>2>>>0]=e):(i()[n>>2>>>0]=e,i()[n+4>>2>>>0]=t)}function $t(t,e){var n=arguments.length-2,r=arguments;return yt((()=>{for(var a=Ce(8*n),i=a>>3,u=0;u<n;u++){var c=r[2+u];o()[i+u>>>0]=c}return we(t,n,a,e)}))}u.executeNotifiedProxyingQueue=zt,wt=_?()=>{var t=process.hrtime();return 1e3*t[0]+t[1]/1e6}:O?()=>performance.now()-u.__performance_now_clock_drift:()=>performance.now();var qt,Xt=[],Jt={};function Zt(){if(!qt){var t,e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:m||"./this.program"};for(t in Jt)void 0===Jt[t]?delete e[t]:e[t]=Jt[t];var n=[];for(t in e)n.push(t+"="+e[t]);qt=n}return qt}function Qt(t,n){if(O)return $t(20,1,t,n);var r=0;return Zt().forEach((function(a,o){var u=n+r;for(o=i()[t+4*o>>2>>>0]=u,u=0;u<a.length;++u)e()[o++>>0>>>0]=a.charCodeAt(u);e()[o>>0>>>0]=0,r+=a.length+1})),0}function Kt(t,e){if(O)return $t(21,1,t,e);var n=Zt();i()[t>>2>>>0]=n.length;var r=0;return n.forEach((function(t){r+=t.length+1})),i()[e>>2>>>0]=r,0}function te(t){return O?$t(22,1,t):52}function ee(t,e,n,r){return O?$t(23,1,t,e,n,r):52}function ne(t,e,n,r,a){return O?$t(24,1,t,e,n,r,a):70}var re=[null,[],[]];function ae(t,e){var n=re[t];0===e||10===e?((1===t?C:x)(z(n,0)),n.length=0):n.push(e)}function ie(t,e,n,a){if(O)return $t(25,1,t,e,n,a);for(var o=0,u=0;u<n;u++){var c=i()[e>>2>>>0],s=i()[e+4>>2>>>0];e+=8;for(var l=0;l<s;l++)ae(t,r()[c+l>>>0]);o+=s}return i()[a>>2>>>0]=o,0}var oe=0;function ue(t){return 0==t%4&&(0!=t%100||0==t%400)}var ce=[31,29,31,30,31,30,31,31,30,31,30,31],se=[31,28,31,30,31,30,31,31,30,31,30,31];function le(t,n,r,i){function o(t,e,n){for(t="number"==typeof t?t.toString():t||"";t.length<e;)t=n[0]+t;return t}function u(t,e){return o(t,e,"0")}function c(t,e){function n(t){return 0>t?-1:0<t?1:0}var r;return 0===(r=n(t.getFullYear()-e.getFullYear()))&&0===(r=n(t.getMonth()-e.getMonth()))&&(r=n(t.getDate()-e.getDate())),r}function s(t){switch(t.getDay()){case 0:return new Date(t.getFullYear()-1,11,29);case 1:return t;case 2:return new Date(t.getFullYear(),0,3);case 3:return new Date(t.getFullYear(),0,2);case 4:return new Date(t.getFullYear(),0,1);case 5:return new Date(t.getFullYear()-1,11,31);case 6:return new Date(t.getFullYear()-1,11,30)}}function l(t){var e=t.Wb;for(t=new Date(new Date(t.Xb+1900,0,1).getTime());0<e;){var n=t.getMonth(),r=(ue(t.getFullYear())?ce:se)[n];if(!(e>r-t.getDate())){t.setDate(t.getDate()+e);break}e-=r-t.getDate()+1,t.setDate(1),11>n?t.setMonth(n+1):(t.setMonth(0),t.setFullYear(t.getFullYear()+1))}return n=new Date(t.getFullYear()+1,0,4),e=s(new Date(t.getFullYear(),0,4)),n=s(n),0>=c(e,t)?0>=c(n,t)?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var f=a()[i+40>>2>>>0];for(var p in i={Lc:a()[i>>2>>>0],Kc:a()[i+4>>2>>>0],dc:a()[i+8>>2>>>0],jc:a()[i+12>>2>>>0],ec:a()[i+16>>2>>>0],Xb:a()[i+20>>2>>>0],Tb:a()[i+24>>2>>>0],Wb:a()[i+28>>2>>>0],Rc:a()[i+32>>2>>>0],Jc:a()[i+36>>2>>>0],Mc:f?Y(f):""},r=Y(r),f={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})r=r.replace(new RegExp(p,"g"),f[p]);var h="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),d="January February March April May June July August September October November December".split(" ");for(p in f={"%a":function(t){return h[t.Tb].substring(0,3)},"%A":function(t){return h[t.Tb]},"%b":function(t){return d[t.ec].substring(0,3)},"%B":function(t){return d[t.ec]},"%C":function(t){return u((t.Xb+1900)/100|0,2)},"%d":function(t){return u(t.jc,2)},"%e":function(t){return o(t.jc,2," ")},"%g":function(t){return l(t).toString().substring(2)},"%G":function(t){return l(t)},"%H":function(t){return u(t.dc,2)},"%I":function(t){return 0==(t=t.dc)?t=12:12<t&&(t-=12),u(t,2)},"%j":function(t){for(var e=0,n=0;n<=t.ec-1;e+=(ue(t.Xb+1900)?ce:se)[n++]);return u(t.jc+e,3)},"%m":function(t){return u(t.ec+1,2)},"%M":function(t){return u(t.Kc,2)},"%n":function(){return"\\n"},"%p":function(t){return 0<=t.dc&&12>t.dc?"AM":"PM"},"%S":function(t){return u(t.Lc,2)},"%t":function(){return"\\t"},"%u":function(t){return t.Tb||7},"%U":function(t){return u(Math.floor((t.Wb+7-t.Tb)/7),2)},"%V":function(t){var e=Math.floor((t.Wb+7-(t.Tb+6)%7)/7);if(2>=(t.Tb+371-t.Wb-2)%7&&e++,e)53==e&&(4==(n=(t.Tb+371-t.Wb)%7)||3==n&&ue(t.Xb)||(e=1));else{e=52;var n=(t.Tb+7-t.Wb-1)%7;(4==n||5==n&&ue(t.Xb%400-1))&&e++}return u(e,2)},"%w":function(t){return t.Tb},"%W":function(t){return u(Math.floor((t.Wb+7-(t.Tb+6)%7)/7),2)},"%y":function(t){return(t.Xb+1900).toString().substring(2)},"%Y":function(t){return t.Xb+1900},"%z":function(t){var e=0<=(t=t.Jc);return t=Math.abs(t)/60,(e?"+":"-")+String("0000"+(t/60*100+t%60)).slice(-4)},"%Z":function(t){return t.Mc},"%%":function(){return"%"}},r=r.replace(/%%/g,"\\0\\0"),f)r.includes(p)&&(r=r.replace(new RegExp(p,"g"),f[p](i)));return p=function(t){var e=Array(G(t)+1);return B(t,e,0,e.length),e}(r=r.replace(/\\0\\0/g,"%")),p.length>n?0:(function(t,n){e().set(t,n>>>0)}(p,t),p.length-1)}ht.fc();var fe=[null,ft,bt,Et,Ct,xt,Rt,jt,kt,Dt,Pt,Ut,Ft,It,Wt,Ht,Lt,Bt,Gt,Vt,Qt,Kt,te,ee,ne,ie],pe={b:function(t){return de(t+24)+24},n:function(t){return(t=new St(t)).uc()||(t.hc(!0),Ot--),t.ic(!1),_t.push(t),t.sc(),t.vc()},ma:function(t){throw x("Unexpected exception thrown, this is not properly supported - aborting"),H=!0,t},x:function(){Se(0);var t=_t.pop();if(t.Hc()&&!t.kc()){var e=t.Dc();e&&gt(e)(t.Zb),Tt(t.Zb)}At=0},e:function(){var t=At;if(!t)return oe=0;var e=new St(t);e.cc(t);var n=e.bc();if(!n)return oe=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;a<r.length;a++){var i=r[a];if(0===i||i===n)break;if(xe(i,n,e.Sb+16))return oe=i,t}return oe=n,t},l:function(){var t=At;if(!t)return oe=0;var e=new St(t);e.cc(t);var n=e.bc();if(!n)return oe=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;a<r.length;a++){var i=r[a];if(0===i||i===n)break;if(xe(i,n,e.Sb+16))return oe=i,t}return oe=n,t},h:function(){var t=At;if(!t)return oe=0;var e=new St(t);e.cc(t);var n=e.bc();if(!n)return oe=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;a<r.length;a++){var i=r[a];if(0===i||i===n)break;if(xe(i,n,e.Sb+16))return oe=i,t}return oe=n,t},t:Tt,M:function(){var t=_t.pop();t||at("no exception to throw");var e=t.Zb;throw t.kc()||(_t.push(t),t.ic(!0),t.hc(!1),Ot++),At=e,e},c:function(t,e,n){throw new St(t).fc(e,n),At=t,Ot++,t},pa:function(){return Ot},Fa:function(t){ge(t,!w,1,!v),ht.pc()},T:function(t){O?postMessage({cmd:"cleanupThread",thread:t}):st(t)},xa:Mt,j:function(t){throw At||(At=t),t},H:Ct,Ma:xt,ua:Rt,wa:jt,oa:kt,Ka:Dt,Ca:Pt,Ja:Ut,V:Ft,va:It,sa:Wt,La:Ht,ta:Lt,Ta:function(){},X:function(){at("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},Ua:function(){at("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},W:function(){return Date.now()},ya:function(){return 2097152},Oa:function(){return!0},za:function(t,e,n,r){if(t==e)setTimeout((()=>zt(r)));else if(O)postMessage({targetThread:t,cmd:"processProxyingQueue",queue:r});else{if(!(t=ht.Vb[t]))return;t.postMessage({cmd:"processProxyingQueue",queue:r})}return 1},Ea:function(){return-1},Pa:function(t,e){t=new Date(1e3*Yt(t)),a()[e>>2>>>0]=t.getUTCSeconds(),a()[e+4>>2>>>0]=t.getUTCMinutes(),a()[e+8>>2>>>0]=t.getUTCHours(),a()[e+12>>2>>>0]=t.getUTCDate(),a()[e+16>>2>>>0]=t.getUTCMonth(),a()[e+20>>2>>>0]=t.getUTCFullYear()-1900,a()[e+24>>2>>>0]=t.getUTCDay(),t=(t.getTime()-Date.UTC(t.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,a()[e+28>>2>>>0]=t},Qa:function(t,e){t=new Date(1e3*Yt(t)),a()[e>>2>>>0]=t.getSeconds(),a()[e+4>>2>>>0]=t.getMinutes(),a()[e+8>>2>>>0]=t.getHours(),a()[e+12>>2>>>0]=t.getDate(),a()[e+16>>2>>>0]=t.getMonth(),a()[e+20>>2>>>0]=t.getFullYear()-1900,a()[e+24>>2>>>0]=t.getDay();var n=new Date(t.getFullYear(),0,1),r=(t.getTime()-n.getTime())/864e5|0;a()[e+28>>2>>>0]=r,a()[e+36>>2>>>0]=-60*t.getTimezoneOffset(),r=new Date(t.getFullYear(),6,1).getTimezoneOffset(),t=0|(r!=(n=n.getTimezoneOffset())&&t.getTimezoneOffset()==Math.min(n,r)),a()[e+32>>2>>>0]=t},Ra:function(t){var e=new Date(a()[t+20>>2>>>0]+1900,a()[t+16>>2>>>0],a()[t+12>>2>>>0],a()[t+8>>2>>>0],a()[t+4>>2>>>0],a()[t>>2>>>0],0),n=a()[t+32>>2>>>0],r=e.getTimezoneOffset(),i=new Date(e.getFullYear(),0,1),o=new Date(e.getFullYear(),6,1).getTimezoneOffset(),u=i.getTimezoneOffset(),c=Math.min(u,o);return 0>n?a()[t+32>>2>>>0]=Number(o!=u&&c==r):0<n!=(c==r)&&(o=Math.max(u,o),e.setTime(e.getTime()+6e4*((0<n?c:o)-r))),a()[t+24>>2>>>0]=e.getDay(),n=(e.getTime()-i.getTime())/864e5|0,a()[t+28>>2>>>0]=n,a()[t>>2>>>0]=e.getSeconds(),a()[t+4>>2>>>0]=e.getMinutes(),a()[t+8>>2>>>0]=e.getHours(),a()[t+12>>2>>>0]=e.getDate(),a()[t+16>>2>>>0]=e.getMonth(),e.getTime()/1e3|0},Aa:Bt,Ba:Gt,Sa:function t(e,n,r){t.Ac||(t.Ac=!0,Vt(e,n,r))},y:function(){at("")},U:function(){if(!_&&!w){var t="Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread";vt||(vt={}),vt[t]||(vt[t]=1,_&&(t="warning: "+t),x(t))}},ra:function(){return 4294901760},B:wt,Ia:function(t,e,n){r().copyWithin(t>>>0,e>>>0,e+n>>>0)},F:function(){return _?n(993).cpus().length:navigator.hardwareConcurrency},Da:function(t,e,n){Xt.length=e,n>>=3;for(var r=0;r<e;r++)Xt[r]=o()[n+r>>>0];return(0>t?ut[-t-1]:fe[t]).apply(null,Xt)},qa:function(t){var e=r().length;if((t>>>=0)<=e||4294901760<t)return!1;for(var n=1;4>=n;n*=2){var a=e*(1+.2/n);a=Math.min(a,t+100663296);var i=Math;a=Math.max(t,a),i=i.min.call(i,4294901760,a+(65536-a%65536)%65536);t:{try{j.grow(i-D.byteLength+65535>>>16),N(j.buffer);var o=1;break t}catch(t){}o=void 0}if(o)return!0}return!1},Na:function(){throw"unwind"},Ga:Qt,Ha:Kt,J:pt,I:te,S:ee,ga:ne,R:ie,d:function(){return oe},na:function t(r,a){t.lc||(t.lc=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var t=new Uint8Array(1);return()=>(crypto.getRandomValues(t),t[0])}if(_)try{var e=n(Object(function(){var t=new Error("Cannot find module \'crypto\'");throw t.code="MODULE_NOT_FOUND",t}()));return()=>e.randomBytes(1)[0]}catch(t){}return()=>at("randomDevice")}());for(var i=0;i<a;i++)e()[r+i>>0>>>0]=t.lc();return 0},ia:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},ja:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},K:function(t){var e=Ee();try{return gt(t)()}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},f:function(t,e){var n=Ee();try{return gt(t)(e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},P:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},Q:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},k:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},p:function(t,e,n,r){var a=Ee();try{return gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},q:function(t,e,n,r,a){var i=Ee();try{return gt(t)(e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},N:function(t,e,n,r,a,i){var o=Ee();try{return gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},s:function(t,e,n,r,a,i){var o=Ee();try{return gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},w:function(t,e,n,r,a,i,o){var u=Ee();try{return gt(t)(e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},L:function(t,e,n,r,a,i,o,u){var c=Ee();try{return gt(t)(e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},E:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=Ee();try{return gt(t)(e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(Me(p),t!==t+0)throw t;Se(1,0)}},aa:function(t,e,n,r,a,i,o,u){var c=Ee();try{return He(t,e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},_:function(t,e,n,r,a,i,o){var u=Ee();try{return ke(t,e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},Z:function(t,e,n,r,a){var i=Ee();try{return Le(t,e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},ca:function(t,e,n,r){var a=Ee();try{return Ie(t,e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},$:function(t){var e=Ee();try{return je(t)}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},ba:function(t,e){var n=Ee();try{return We(t,e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},Y:function(t,e,n){var r=Ee();try{return De(t,e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},g:function(t){var e=Ee();try{gt(t)()}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},r:function(t,e){var n=Ee();try{gt(t)(e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},i:function(t,e,n){var r=Ee();try{gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},ha:function(t,e,n,r){var a=Ee();try{gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},m:function(t,e,n,r){var a=Ee();try{gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},v:function(t,e,n,r,a){var i=Ee();try{gt(t)(e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},u:function(t,e,n,r,a,i){var o=Ee();try{gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},O:function(t,e,n,r,a,i,o){var u=Ee();try{gt(t)(e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},A:function(t,e,n,r,a,i,o,u){var c=Ee();try{gt(t)(e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},ka:function(t,e,n,r,a,i,o,u,c){var s=Ee();try{gt(t)(e,n,r,a,i,o,u,c)}catch(t){if(Me(s),t!==t+0)throw t;Se(1,0)}},C:function(t,e,n,r,a,i,o,u,c,s,l){var f=Ee();try{gt(t)(e,n,r,a,i,o,u,c,s,l)}catch(t){if(Me(f),t!==t+0)throw t;Se(1,0)}},D:function(t,e,n,r,a,i,o,u,c,s,l,f,p,h,d,y){var b=Ee();try{gt(t)(e,n,r,a,i,o,u,c,s,l,f,p,h,d,y)}catch(t){if(Me(b),t!==t+0)throw t;Se(1,0)}},fa:function(t,e,n,r,a,i,o,u){var c=Ee();try{Pe(t,e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},da:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=Ee();try{Fe(t,e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(Me(p),t!==t+0)throw t;Se(1,0)}},ea:function(t,e,n,r,a,i){var o=Ee();try{Ue(t,e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},o:function(t){return t},a:j||u.wasmMemory,G:function(t){oe=t},la:le,z:function(t,e,n,r){return le(t,e,n,r)}};!function(){function t(t,e){u.asm=t.exports,ht.qc.push(u.asm.sb),$=u.asm.ub,X.unshift(u.asm.Va),k=e,O||(et--,u.monitorRunDependencies&&u.monitorRunDependencies(et),0==et&&(null!==nt&&(clearInterval(nt),nt=null),rt&&(t=rt,rt=null,t())))}function e(e){t(e.instance,e.module)}function n(t){return function(){if(!M&&(v||w)){if("function"==typeof fetch&&!tt.startsWith("file://"))return fetch(tt,{credentials:"same-origin"}).then((function(t){if(!t.ok)throw"failed to load wasm binary file at \'"+tt+"\'";return t.arrayBuffer()})).catch((function(){return ot()}));if(f)return new Promise((function(t,e){f(tt,(function(e){t(new Uint8Array(e))}),e)}))}return Promise.resolve().then((function(){return ot()}))}().then((function(t){return WebAssembly.instantiate(t,r)})).then((function(t){return t})).then(t,(function(t){x("failed to asynchronously prepare wasm: "+t),at(t)}))}var r={a:pe};if(O||(et++,u.monitorRunDependencies&&u.monitorRunDependencies(et)),u.instantiateWasm)try{return u.instantiateWasm(r,t)}catch(t){return x("Module.instantiateWasm callback failed with error: "+t),!1}(M||"function"!=typeof WebAssembly.instantiateStreaming||it()||tt.startsWith("file://")||_||"function"!=typeof fetch?n(e):fetch(tt,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,r).then(e,(function(t){return x("wasm streaming compile failed: "+t),x("falling back to ArrayBuffer instantiation"),n(e)}))}))).catch(s)}(),u.___wasm_call_ctors=function(){return(u.___wasm_call_ctors=u.asm.Va).apply(null,arguments)},u._OrtInit=function(){return(u._OrtInit=u.asm.Wa).apply(null,arguments)},u._OrtCreateSessionOptions=function(){return(u._OrtCreateSessionOptions=u.asm.Xa).apply(null,arguments)},u._OrtAppendExecutionProvider=function(){return(u._OrtAppendExecutionProvider=u.asm.Ya).apply(null,arguments)},u._OrtAddSessionConfigEntry=function(){return(u._OrtAddSessionConfigEntry=u.asm.Za).apply(null,arguments)},u._OrtReleaseSessionOptions=function(){return(u._OrtReleaseSessionOptions=u.asm._a).apply(null,arguments)},u._OrtCreateSession=function(){return(u._OrtCreateSession=u.asm.$a).apply(null,arguments)},u._OrtReleaseSession=function(){return(u._OrtReleaseSession=u.asm.ab).apply(null,arguments)},u._OrtGetInputCount=function(){return(u._OrtGetInputCount=u.asm.bb).apply(null,arguments)},u._OrtGetOutputCount=function(){return(u._OrtGetOutputCount=u.asm.cb).apply(null,arguments)},u._OrtGetInputName=function(){return(u._OrtGetInputName=u.asm.db).apply(null,arguments)},u._OrtGetOutputName=function(){return(u._OrtGetOutputName=u.asm.eb).apply(null,arguments)},u._OrtFree=function(){return(u._OrtFree=u.asm.fb).apply(null,arguments)},u._OrtCreateTensor=function(){return(u._OrtCreateTensor=u.asm.gb).apply(null,arguments)},u._OrtGetTensorData=function(){return(u._OrtGetTensorData=u.asm.hb).apply(null,arguments)},u._OrtReleaseTensor=function(){return(u._OrtReleaseTensor=u.asm.ib).apply(null,arguments)},u._OrtCreateRunOptions=function(){return(u._OrtCreateRunOptions=u.asm.jb).apply(null,arguments)},u._OrtAddRunConfigEntry=function(){return(u._OrtAddRunConfigEntry=u.asm.kb).apply(null,arguments)},u._OrtReleaseRunOptions=function(){return(u._OrtReleaseRunOptions=u.asm.lb).apply(null,arguments)},u._OrtRun=function(){return(u._OrtRun=u.asm.mb).apply(null,arguments)},u._OrtEndProfiling=function(){return(u._OrtEndProfiling=u.asm.nb).apply(null,arguments)};var he=u._pthread_self=function(){return(he=u._pthread_self=u.asm.ob).apply(null,arguments)},de=u._malloc=function(){return(de=u._malloc=u.asm.pb).apply(null,arguments)},ye=u._free=function(){return(ye=u._free=u.asm.qb).apply(null,arguments)},be=u._fflush=function(){return(be=u._fflush=u.asm.rb).apply(null,arguments)};u.__emscripten_tls_init=function(){return(u.__emscripten_tls_init=u.asm.sb).apply(null,arguments)};var me=u.___funcs_on_exit=function(){return(me=u.___funcs_on_exit=u.asm.tb).apply(null,arguments)},ge=u.__emscripten_thread_init=function(){return(ge=u.__emscripten_thread_init=u.asm.vb).apply(null,arguments)};u.__emscripten_thread_crashed=function(){return(u.__emscripten_thread_crashed=u.asm.wb).apply(null,arguments)};var ve,we=u._emscripten_run_in_main_runtime_thread_js=function(){return(we=u._emscripten_run_in_main_runtime_thread_js=u.asm.xb).apply(null,arguments)},_e=u.__emscripten_proxy_execute_task_queue=function(){return(_e=u.__emscripten_proxy_execute_task_queue=u.asm.yb).apply(null,arguments)},Oe=u.__emscripten_thread_free_data=function(){return(Oe=u.__emscripten_thread_free_data=u.asm.zb).apply(null,arguments)},Ae=u.__emscripten_thread_exit=function(){return(Ae=u.__emscripten_thread_exit=u.asm.Ab).apply(null,arguments)},Se=u._setThrew=function(){return(Se=u._setThrew=u.asm.Bb).apply(null,arguments)},Te=u._emscripten_stack_set_limits=function(){return(Te=u._emscripten_stack_set_limits=u.asm.Cb).apply(null,arguments)},Ee=u.stackSave=function(){return(Ee=u.stackSave=u.asm.Db).apply(null,arguments)},Me=u.stackRestore=function(){return(Me=u.stackRestore=u.asm.Eb).apply(null,arguments)},Ce=u.stackAlloc=function(){return(Ce=u.stackAlloc=u.asm.Fb).apply(null,arguments)},xe=u.___cxa_can_catch=function(){return(xe=u.___cxa_can_catch=u.asm.Gb).apply(null,arguments)},Re=u.___cxa_is_pointer_type=function(){return(Re=u.___cxa_is_pointer_type=u.asm.Hb).apply(null,arguments)},je=u.dynCall_j=function(){return(je=u.dynCall_j=u.asm.Ib).apply(null,arguments)},ke=u.dynCall_iiiiij=function(){return(ke=u.dynCall_iiiiij=u.asm.Jb).apply(null,arguments)},De=u.dynCall_jii=function(){return(De=u.dynCall_jii=u.asm.Kb).apply(null,arguments)},Pe=u.dynCall_viiiiij=function(){return(Pe=u.dynCall_viiiiij=u.asm.Lb).apply(null,arguments)},Ue=u.dynCall_vjji=function(){return(Ue=u.dynCall_vjji=u.asm.Mb).apply(null,arguments)},Fe=u.dynCall_viiijjjii=function(){return(Fe=u.dynCall_viiijjjii=u.asm.Nb).apply(null,arguments)},Ie=u.dynCall_iij=function(){return(Ie=u.dynCall_iij=u.asm.Ob).apply(null,arguments)},We=u.dynCall_ji=function(){return(We=u.dynCall_ji=u.asm.Pb).apply(null,arguments)},He=u.dynCall_iiiiiij=function(){return(He=u.dynCall_iiiiiij=u.asm.Qb).apply(null,arguments)},Le=u.dynCall_iiij=function(){return(Le=u.dynCall_iiij=u.asm.Rb).apply(null,arguments)};function ze(){function t(){if(!ve&&(ve=!0,u.calledRun=!0,!H)&&(O||dt(X),c(u),u.onRuntimeInitialized&&u.onRuntimeInitialized(),!O)){if(u.postRun)for("function"==typeof u.postRun&&(u.postRun=[u.postRun]);u.postRun.length;){var t=u.postRun.shift();Z.unshift(t)}dt(Z)}}if(!(0<et))if(O)c(u),O||dt(X),postMessage({cmd:"loaded"});else{if(u.preRun)for("function"==typeof u.preRun&&(u.preRun=[u.preRun]);u.preRun.length;)K();dt(q),0<et||(u.setStatus?(u.setStatus("Running..."),setTimeout((function(){setTimeout((function(){u.setStatus("")}),1),t()}),1)):t())}}if(u.UTF8ToString=Y,u.stringToUTF8=function(t,e,n){return B(t,r(),e,n)},u.lengthBytesUTF8=G,u.keepRuntimeAlive=Q,u.wasmMemory=j,u.stackSave=Ee,u.stackRestore=Me,u.stackAlloc=Ce,u.ExitStatus=ct,u.PThread=ht,rt=function t(){ve||ze(),ve||(rt=t)},u.preInit)for("function"==typeof u.preInit&&(u.preInit=[u.preInit]);0<u.preInit.length;)u.preInit.pop()();return ze(),t.ready});t.exports=r},932:(t,e,n)=>{var _scriptDir,r=(_scriptDir=(_scriptDir="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(t){var e,r,a;t=t||{},e||(e=void 0!==t?t:{}),e.ready=new Promise((function(t,e){r=t,a=e}));var i,o,u,c,s,l,f=Object.assign({},e),p="./this.program",h=(t,e)=>{throw e},d="object"==typeof window,y="function"==typeof importScripts,b="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,m="";b?(m=y?n(908).dirname(m)+"/":"//",l=()=>{s||(c=n(384),s=n(908))},i=function(t,e){return l(),t=s.normalize(t),c.readFileSync(t,e?void 0:"utf8")},u=t=>((t=i(t,!0)).buffer||(t=new Uint8Array(t)),t),o=(t,e,n)=>{l(),t=s.normalize(t),c.readFile(t,(function(t,r){t?n(t):e(r.buffer)}))},1<process.argv.length&&(p=process.argv[1].replace(/\\\\/g,"/")),process.argv.slice(2),process.on("uncaughtException",(function(t){if(!(t instanceof J))throw t})),process.on("unhandledRejection",(function(t){throw t})),h=(t,e)=>{if(_||0<L)throw process.exitCode=t,e;e instanceof J||w("exiting due to exception: "+e),process.exit(t)},e.inspect=function(){return"[Emscripten Module object]"}):(d||y)&&(y?m=self.location.href:"undefined"!=typeof document&&document.currentScript&&(m=document.currentScript.src),_scriptDir&&(m=_scriptDir),m=0!==m.indexOf("blob:")?m.substr(0,m.replace(/[?#].*/,"").lastIndexOf("/")+1):"",i=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.send(null),e.responseText},y&&(u=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),o=(t,e,n)=>{var r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?e(r.response):n()},r.onerror=n,r.send(null)});var g,v=e.print||console.log.bind(console),w=e.printErr||console.warn.bind(console);Object.assign(e,f),f=null,e.thisProgram&&(p=e.thisProgram),e.quit&&(h=e.quit),e.wasmBinary&&(g=e.wasmBinary);var _=e.noExitRuntime||!1;"object"!=typeof WebAssembly&&V("no native wasm support detected");var O,A,S,T,E,M,C=!1,x="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function R(t,e,n){var r=(e>>>=0)+n;for(n=e;t[n]&&!(n>=r);)++n;if(16<n-e&&t.buffer&&x)return x.decode(t.subarray(e,n));for(r="";e<n;){var a=t[e++];if(128&a){var i=63&t[e++];if(192==(224&a))r+=String.fromCharCode((31&a)<<6|i);else{var o=63&t[e++];65536>(a=224==(240&a)?(15&a)<<12|i<<6|o:(7&a)<<18|i<<12|o<<6|63&t[e++])?r+=String.fromCharCode(a):(a-=65536,r+=String.fromCharCode(55296|a>>10,56320|1023&a))}}else r+=String.fromCharCode(a)}return r}function j(t,e){return(t>>>=0)?R(T,t,e):""}function k(t,e,n,r){if(!(0<r))return 0;var a=n>>>=0;r=n+r-1;for(var i=0;i<t.length;++i){var o=t.charCodeAt(i);if(55296<=o&&57343>=o&&(o=65536+((1023&o)<<10)|1023&t.charCodeAt(++i)),127>=o){if(n>=r)break;e[n++>>>0]=o}else{if(2047>=o){if(n+1>=r)break;e[n++>>>0]=192|o>>6}else{if(65535>=o){if(n+2>=r)break;e[n++>>>0]=224|o>>12}else{if(n+3>=r)break;e[n++>>>0]=240|o>>18,e[n++>>>0]=128|o>>12&63}e[n++>>>0]=128|o>>6&63}e[n++>>>0]=128|63&o}}return e[n>>>0]=0,n-a}function D(t){for(var e=0,n=0;n<t.length;++n){var r=t.charCodeAt(n);127>=r?e++:2047>=r?e+=2:55296<=r&&57343>=r?(e+=4,++n):e+=3}return e}function P(){var t=O.buffer;A=t,e.HEAP8=S=new Int8Array(t),e.HEAP16=new Int16Array(t),e.HEAP32=E=new Int32Array(t),e.HEAPU8=T=new Uint8Array(t),e.HEAPU16=new Uint16Array(t),e.HEAPU32=M=new Uint32Array(t),e.HEAPF32=new Float32Array(t),e.HEAPF64=new Float64Array(t)}var U,F=[],I=[],W=[],H=[],L=0;function z(){var t=e.preRun.shift();F.unshift(t)}var Y,B=0,G=null,N=null;function V(t){throw e.onAbort&&e.onAbort(t),w(t="Aborted("+t+")"),C=!0,t=new WebAssembly.RuntimeError(t+". Build with -sASSERTIONS for more info."),a(t),t}function $(){return Y.startsWith("data:application/octet-stream;base64,")}if(Y="ort-wasm.wasm",!$()){var q=Y;Y=e.locateFile?e.locateFile(q,m):m+q}function X(){var t=Y;try{if(t==Y&&g)return new Uint8Array(g);if(u)return u(t);throw"both async and sync fetching of the wasm failed"}catch(t){V(t)}}function J(t){this.name="ExitStatus",this.message="Program terminated with exit("+t+")",this.status=t}function Z(t){for(;0<t.length;)t.shift()(e)}var Q=[],K=0,tt=0;function et(t){this.Db=t,this.zb=t-24,this.Ub=function(t){M[this.zb+4>>2>>>0]=t},this.Eb=function(){return M[this.zb+4>>2>>>0]},this.Sb=function(t){M[this.zb+8>>2>>>0]=t},this.Wb=function(){return M[this.zb+8>>2>>>0]},this.Tb=function(){E[this.zb>>2>>>0]=0},this.Ib=function(t){S[this.zb+12>>0>>>0]=t?1:0},this.Pb=function(){return 0!=S[this.zb+12>>0>>>0]},this.Jb=function(t){S[this.zb+13>>0>>>0]=t?1:0},this.Lb=function(){return 0!=S[this.zb+13>>0>>>0]},this.Rb=function(t,e){this.Fb(0),this.Ub(t),this.Sb(e),this.Tb(),this.Ib(!1),this.Jb(!1)},this.Nb=function(){E[this.zb>>2>>>0]+=1},this.Xb=function(){var t=E[this.zb>>2>>>0];return E[this.zb>>2>>>0]=t-1,1===t},this.Fb=function(t){M[this.zb+16>>2>>>0]=t},this.Ob=function(){return M[this.zb+16>>2>>>0]},this.Qb=function(){if(Mt(this.Eb()))return M[this.Db>>2>>>0];var t=this.Ob();return 0!==t?t:this.Db}}function nt(t){return vt(new et(t).zb)}var rt=[];function at(t){var e=rt[t];return e||(t>=rt.length&&(rt.length=t+1),rt[t]=e=U.get(t)),e}function it(t){var e=D(t)+1,n=gt(e);return n&&k(t,S,n,e),n}var ot={};function ut(){if(!ct){var t,e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:p||"./this.program"};for(t in ot)void 0===ot[t]?delete e[t]:e[t]=ot[t];var n=[];for(t in e)n.push(t+"="+e[t]);ct=n}return ct}var ct,st=[null,[],[]];function lt(t,e){var n=st[t];0===e||10===e?((1===t?v:w)(R(n,0)),n.length=0):n.push(e)}var ft=0;function pt(t){return 0==t%4&&(0!=t%100||0==t%400)}var ht=[31,29,31,30,31,30,31,31,30,31,30,31],dt=[31,28,31,30,31,30,31,31,30,31,30,31];function yt(t,e,n,r){function a(t,e,n){for(t="number"==typeof t?t.toString():t||"";t.length<e;)t=n[0]+t;return t}function i(t,e){return a(t,e,"0")}function o(t,e){function n(t){return 0>t?-1:0<t?1:0}var r;return 0===(r=n(t.getFullYear()-e.getFullYear()))&&0===(r=n(t.getMonth()-e.getMonth()))&&(r=n(t.getDate()-e.getDate())),r}function u(t){switch(t.getDay()){case 0:return new Date(t.getFullYear()-1,11,29);case 1:return t;case 2:return new Date(t.getFullYear(),0,3);case 3:return new Date(t.getFullYear(),0,2);case 4:return new Date(t.getFullYear(),0,1);case 5:return new Date(t.getFullYear()-1,11,31);case 6:return new Date(t.getFullYear()-1,11,30)}}function c(t){var e=t.Bb;for(t=new Date(new Date(t.Cb+1900,0,1).getTime());0<e;){var n=t.getMonth(),r=(pt(t.getFullYear())?ht:dt)[n];if(!(e>r-t.getDate())){t.setDate(t.getDate()+e);break}e-=r-t.getDate()+1,t.setDate(1),11>n?t.setMonth(n+1):(t.setMonth(0),t.setFullYear(t.getFullYear()+1))}return n=new Date(t.getFullYear()+1,0,4),e=u(new Date(t.getFullYear(),0,4)),n=u(n),0>=o(e,t)?0>=o(n,t)?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var s=E[r+40>>2>>>0];for(var l in r={$b:E[r>>2>>>0],Zb:E[r+4>>2>>>0],Gb:E[r+8>>2>>>0],Kb:E[r+12>>2>>>0],Hb:E[r+16>>2>>>0],Cb:E[r+20>>2>>>0],Ab:E[r+24>>2>>>0],Bb:E[r+28>>2>>>0],bc:E[r+32>>2>>>0],Yb:E[r+36>>2>>>0],ac:s?j(s):""},n=j(n),s={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})n=n.replace(new RegExp(l,"g"),s[l]);var f="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),p="January February March April May June July August September October November December".split(" ");for(l in s={"%a":function(t){return f[t.Ab].substring(0,3)},"%A":function(t){return f[t.Ab]},"%b":function(t){return p[t.Hb].substring(0,3)},"%B":function(t){return p[t.Hb]},"%C":function(t){return i((t.Cb+1900)/100|0,2)},"%d":function(t){return i(t.Kb,2)},"%e":function(t){return a(t.Kb,2," ")},"%g":function(t){return c(t).toString().substring(2)},"%G":function(t){return c(t)},"%H":function(t){return i(t.Gb,2)},"%I":function(t){return 0==(t=t.Gb)?t=12:12<t&&(t-=12),i(t,2)},"%j":function(t){for(var e=0,n=0;n<=t.Hb-1;e+=(pt(t.Cb+1900)?ht:dt)[n++]);return i(t.Kb+e,3)},"%m":function(t){return i(t.Hb+1,2)},"%M":function(t){return i(t.Zb,2)},"%n":function(){return"\\n"},"%p":function(t){return 0<=t.Gb&&12>t.Gb?"AM":"PM"},"%S":function(t){return i(t.$b,2)},"%t":function(){return"\\t"},"%u":function(t){return t.Ab||7},"%U":function(t){return i(Math.floor((t.Bb+7-t.Ab)/7),2)},"%V":function(t){var e=Math.floor((t.Bb+7-(t.Ab+6)%7)/7);if(2>=(t.Ab+371-t.Bb-2)%7&&e++,e)53==e&&(4==(n=(t.Ab+371-t.Bb)%7)||3==n&&pt(t.Cb)||(e=1));else{e=52;var n=(t.Ab+7-t.Bb-1)%7;(4==n||5==n&&pt(t.Cb%400-1))&&e++}return i(e,2)},"%w":function(t){return t.Ab},"%W":function(t){return i(Math.floor((t.Bb+7-(t.Ab+6)%7)/7),2)},"%y":function(t){return(t.Cb+1900).toString().substring(2)},"%Y":function(t){return t.Cb+1900},"%z":function(t){var e=0<=(t=t.Yb);return t=Math.abs(t)/60,(e?"+":"-")+String("0000"+(t/60*100+t%60)).slice(-4)},"%Z":function(t){return t.ac},"%%":function(){return"%"}},n=n.replace(/%%/g,"\\0\\0"),s)n.includes(l)&&(n=n.replace(new RegExp(l,"g"),s[l](r)));return l=function(t){var e=Array(D(t)+1);return k(t,e,0,e.length),e}(n=n.replace(/\\0\\0/g,"%")),l.length>e?0:(S.set(l,t>>>0),l.length-1)}var bt={a:function(t){return gt(t+24)+24},m:function(t){return(t=new et(t)).Pb()||(t.Ib(!0),K--),t.Jb(!1),Q.push(t),t.Nb(),t.Qb()},ia:function(t){throw w("Unexpected exception thrown, this is not properly supported - aborting"),C=!0,t},w:function(){Ot(0);var t=Q.pop();if(t.Xb()&&!t.Lb()){var e=t.Wb();e&&at(e)(t.Db),nt(t.Db)}tt=0},d:function(){var t=tt;if(!t)return ft=0;var e=new et(t);e.Fb(t);var n=e.Eb();if(!n)return ft=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;a<r.length;a++){var i=r[a];if(0===i||i===n)break;if(Et(i,n,e.zb+16))return ft=i,t}return ft=n,t},k:function(){var t=tt;if(!t)return ft=0;var e=new et(t);e.Fb(t);var n=e.Eb();if(!n)return ft=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;a<r.length;a++){var i=r[a];if(0===i||i===n)break;if(Et(i,n,e.zb+16))return ft=i,t}return ft=n,t},g:function(){var t=tt;if(!t)return ft=0;var e=new et(t);e.Fb(t);var n=e.Eb();if(!n)return ft=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;a<r.length;a++){var i=r[a];if(0===i||i===n)break;if(Et(i,n,e.zb+16))return ft=i,t}return ft=n,t},s:nt,L:function(){var t=Q.pop();t||V("no exception to throw");var e=t.Db;throw t.Lb()||(Q.push(t),t.Jb(!0),t.Ib(!1),K++),tt=e,e},b:function(t,e,n){throw new et(t).Rb(e,n),tt=t,K++,t},la:function(){return K},i:function(t){throw tt||(tt=t),t},H:function(){return 0},Ba:function(){},pa:function(){},ra:function(){},ka:function(){return 0},za:function(){},ua:function(){},ya:function(){},R:function(){},qa:function(){},na:function(){},Aa:function(){},oa:function(){},Ha:function(){},Ja:function(){V("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},Ia:function(){V("To use dlopen, you need enable dynamic linking, see https://github.com/emscripten-core/emscripten/wiki/Linking")},S:function(){return Date.now()},Ca:function(){return!0},Da:function(t,e){t=new Date(1e3*(M[t>>>2]+4294967296*E[t+4>>>2])),E[e>>2>>>0]=t.getUTCSeconds(),E[e+4>>2>>>0]=t.getUTCMinutes(),E[e+8>>2>>>0]=t.getUTCHours(),E[e+12>>2>>>0]=t.getUTCDate(),E[e+16>>2>>>0]=t.getUTCMonth(),E[e+20>>2>>>0]=t.getUTCFullYear()-1900,E[e+24>>2>>>0]=t.getUTCDay(),E[e+28>>2>>>0]=(t.getTime()-Date.UTC(t.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},Ea:function(t,e){t=new Date(1e3*(M[t>>>2]+4294967296*E[t+4>>>2])),E[e>>2>>>0]=t.getSeconds(),E[e+4>>2>>>0]=t.getMinutes(),E[e+8>>2>>>0]=t.getHours(),E[e+12>>2>>>0]=t.getDate(),E[e+16>>2>>>0]=t.getMonth(),E[e+20>>2>>>0]=t.getFullYear()-1900,E[e+24>>2>>>0]=t.getDay();var n=new Date(t.getFullYear(),0,1);E[e+28>>2>>>0]=(t.getTime()-n.getTime())/864e5|0,E[e+36>>2>>>0]=-60*t.getTimezoneOffset();var r=new Date(t.getFullYear(),6,1).getTimezoneOffset();n=n.getTimezoneOffset(),E[e+32>>2>>>0]=0|(r!=n&&t.getTimezoneOffset()==Math.min(n,r))},Fa:function(t){var e=new Date(E[t+20>>2>>>0]+1900,E[t+16>>2>>>0],E[t+12>>2>>>0],E[t+8>>2>>>0],E[t+4>>2>>>0],E[t>>2>>>0],0),n=E[t+32>>2>>>0],r=e.getTimezoneOffset(),a=new Date(e.getFullYear(),0,1),i=new Date(e.getFullYear(),6,1).getTimezoneOffset(),o=a.getTimezoneOffset(),u=Math.min(o,i);return 0>n?E[t+32>>2>>>0]=Number(i!=o&&u==r):0<n!=(u==r)&&(i=Math.max(o,i),e.setTime(e.getTime()+6e4*((0<n?u:i)-r))),E[t+24>>2>>>0]=e.getDay(),E[t+28>>2>>>0]=(e.getTime()-a.getTime())/864e5|0,E[t>>2>>>0]=e.getSeconds(),E[t+4>>2>>>0]=e.getMinutes(),E[t+8>>2>>>0]=e.getHours(),E[t+12>>2>>>0]=e.getDate(),E[t+16>>2>>>0]=e.getMonth(),e.getTime()/1e3|0},sa:function(){return-52},ta:function(){},Ga:function t(e,n,r){t.Vb||(t.Vb=!0,function(t,e,n){function r(t){return(t=t.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?t[1]:"GMT"}var a=(new Date).getFullYear(),i=new Date(a,0,1),o=new Date(a,6,1);a=i.getTimezoneOffset();var u=o.getTimezoneOffset();E[t>>2>>>0]=60*Math.max(a,u),E[e>>2>>>0]=Number(a!=u),t=r(i),e=r(o),t=it(t),e=it(e),u<a?(M[n>>2>>>0]=t,M[n+4>>2>>>0]=e):(M[n>>2>>>0]=e,M[n+4>>2>>>0]=t)}(e,n,r))},B:function(){V("")},ma:function(){return 4294901760},I:b?()=>{var t=process.hrtime();return 1e3*t[0]+t[1]/1e6}:()=>performance.now(),xa:function(t,e,n){T.copyWithin(t>>>0,e>>>0,e+n>>>0)},G:function(t){var e=T.length;if(4294901760<(t>>>=0))return!1;for(var n=1;4>=n;n*=2){var r=e*(1+.2/n);r=Math.min(r,t+100663296);var a=Math;r=Math.max(t,r),a=a.min.call(a,4294901760,r+(65536-r%65536)%65536);t:{try{O.grow(a-A.byteLength+65535>>>16),P();var i=1;break t}catch(t){}i=void 0}if(i)return!0}return!1},va:function(t,e){var n=0;return ut().forEach((function(r,a){var i=e+n;for(a=M[t+4*a>>2>>>0]=i,i=0;i<r.length;++i)S[a++>>0>>>0]=r.charCodeAt(i);S[a>>0>>>0]=0,n+=r.length+1})),0},wa:function(t,e){var n=ut();M[t>>2>>>0]=n.length;var r=0;return n.forEach((function(t){r+=t.length+1})),M[e>>2>>>0]=r,0},ba:function(t){_||0<L||(_t(),Z(W),wt(0),st[1].length&&lt(1,10),st[2].length&&lt(2,10)),_||0<L||(e.onExit&&e.onExit(t),C=!0),h(t,new J(t))},E:function(){return 52},Q:function(){return 52},ca:function(){return 70},P:function(t,e,n,r){for(var a=0,i=0;i<n;i++){var o=M[e>>2>>>0],u=M[e+4>>2>>>0];e+=8;for(var c=0;c<u;c++)lt(t,T[o+c>>>0]);a+=u}return M[r>>2>>>0]=a,0},c:function(){return ft},ja:function t(e,r){t.Mb||(t.Mb=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var t=new Uint8Array(1);return()=>(crypto.getRandomValues(t),t[0])}if(b)try{var e=n(Object(function(){var t=new Error("Cannot find module \'crypto\'");throw t.code="MODULE_NOT_FOUND",t}()));return()=>e.randomBytes(1)[0]}catch(t){}return()=>V("randomDevice")}());for(var a=0;a<r;a++)S[e+a>>0>>>0]=t.Mb();return 0},ea:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},fa:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},J:function(t){var e=At();try{return at(t)()}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},e:function(t,e){var n=At();try{return at(t)(e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},N:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},O:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},j:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},o:function(t,e,n,r){var a=At();try{return at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},p:function(t,e,n,r,a){var i=At();try{return at(t)(e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},M:function(t,e,n,r,a,i){var o=At();try{return at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},r:function(t,e,n,r,a,i){var o=At();try{return at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},v:function(t,e,n,r,a,i,o){var u=At();try{return at(t)(e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},K:function(t,e,n,r,a,i,o,u){var c=At();try{return at(t)(e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},D:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=At();try{return at(t)(e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(St(p),t!==t+0)throw t;Ot(1,0)}},X:function(t,e,n,r,a,i,o,u){var c=At();try{return Ft(t,e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},V:function(t,e,n,r,a,i,o){var u=At();try{return xt(t,e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},U:function(t,e,n,r,a){var i=At();try{return It(t,e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},Z:function(t,e,n,r){var a=At();try{return Pt(t,e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},W:function(t){var e=At();try{return Ct(t)}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},Y:function(t,e){var n=At();try{return Ut(t,e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},T:function(t,e,n){var r=At();try{return Rt(t,e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},f:function(t){var e=At();try{at(t)()}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},q:function(t,e){var n=At();try{at(t)(e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},h:function(t,e,n){var r=At();try{at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},da:function(t,e,n,r){var a=At();try{at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},l:function(t,e,n,r){var a=At();try{at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},t:function(t,e,n,r,a){var i=At();try{at(t)(e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},u:function(t,e,n,r,a,i){var o=At();try{at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},x:function(t,e,n,r,a,i,o){var u=At();try{at(t)(e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},z:function(t,e,n,r,a,i,o,u){var c=At();try{at(t)(e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},ga:function(t,e,n,r,a,i,o,u,c){var s=At();try{at(t)(e,n,r,a,i,o,u,c)}catch(t){if(St(s),t!==t+0)throw t;Ot(1,0)}},A:function(t,e,n,r,a,i,o,u,c,s,l){var f=At();try{at(t)(e,n,r,a,i,o,u,c,s,l)}catch(t){if(St(f),t!==t+0)throw t;Ot(1,0)}},C:function(t,e,n,r,a,i,o,u,c,s,l,f,p,h,d,y){var b=At();try{at(t)(e,n,r,a,i,o,u,c,s,l,f,p,h,d,y)}catch(t){if(St(b),t!==t+0)throw t;Ot(1,0)}},aa:function(t,e,n,r,a,i,o,u){var c=At();try{jt(t,e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},_:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=At();try{Dt(t,e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(St(p),t!==t+0)throw t;Ot(1,0)}},$:function(t,e,n,r,a,i){var o=At();try{kt(t,e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},n:function(t){return t},F:function(t){ft=t},ha:yt,y:function(t,e,n,r){return yt(t,e,n,r)}};!function(){function t(t){e.asm=t.exports,O=e.asm.Ka,P(),U=e.asm.ib,I.unshift(e.asm.La),B--,e.monitorRunDependencies&&e.monitorRunDependencies(B),0==B&&(null!==G&&(clearInterval(G),G=null),N&&(t=N,N=null,t()))}function n(e){t(e.instance)}function r(t){return function(){if(!g&&(d||y)){if("function"==typeof fetch&&!Y.startsWith("file://"))return fetch(Y,{credentials:"same-origin"}).then((function(t){if(!t.ok)throw"failed to load wasm binary file at \'"+Y+"\'";return t.arrayBuffer()})).catch((function(){return X()}));if(o)return new Promise((function(t,e){o(Y,(function(e){t(new Uint8Array(e))}),e)}))}return Promise.resolve().then((function(){return X()}))}().then((function(t){return WebAssembly.instantiate(t,i)})).then((function(t){return t})).then(t,(function(t){w("failed to asynchronously prepare wasm: "+t),V(t)}))}var i={a:bt};if(B++,e.monitorRunDependencies&&e.monitorRunDependencies(B),e.instantiateWasm)try{return e.instantiateWasm(i,t)}catch(t){return w("Module.instantiateWasm callback failed with error: "+t),!1}(g||"function"!=typeof WebAssembly.instantiateStreaming||$()||Y.startsWith("file://")||b||"function"!=typeof fetch?r(n):fetch(Y,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,i).then(n,(function(t){return w("wasm streaming compile failed: "+t),w("falling back to ArrayBuffer instantiation"),r(n)}))}))).catch(a)}(),e.___wasm_call_ctors=function(){return(e.___wasm_call_ctors=e.asm.La).apply(null,arguments)},e._OrtInit=function(){return(e._OrtInit=e.asm.Ma).apply(null,arguments)},e._OrtCreateSessionOptions=function(){return(e._OrtCreateSessionOptions=e.asm.Na).apply(null,arguments)},e._OrtAppendExecutionProvider=function(){return(e._OrtAppendExecutionProvider=e.asm.Oa).apply(null,arguments)},e._OrtAddSessionConfigEntry=function(){return(e._OrtAddSessionConfigEntry=e.asm.Pa).apply(null,arguments)},e._OrtReleaseSessionOptions=function(){return(e._OrtReleaseSessionOptions=e.asm.Qa).apply(null,arguments)},e._OrtCreateSession=function(){return(e._OrtCreateSession=e.asm.Ra).apply(null,arguments)},e._OrtReleaseSession=function(){return(e._OrtReleaseSession=e.asm.Sa).apply(null,arguments)},e._OrtGetInputCount=function(){return(e._OrtGetInputCount=e.asm.Ta).apply(null,arguments)},e._OrtGetOutputCount=function(){return(e._OrtGetOutputCount=e.asm.Ua).apply(null,arguments)},e._OrtGetInputName=function(){return(e._OrtGetInputName=e.asm.Va).apply(null,arguments)},e._OrtGetOutputName=function(){return(e._OrtGetOutputName=e.asm.Wa).apply(null,arguments)},e._OrtFree=function(){return(e._OrtFree=e.asm.Xa).apply(null,arguments)},e._OrtCreateTensor=function(){return(e._OrtCreateTensor=e.asm.Ya).apply(null,arguments)},e._OrtGetTensorData=function(){return(e._OrtGetTensorData=e.asm.Za).apply(null,arguments)},e._OrtReleaseTensor=function(){return(e._OrtReleaseTensor=e.asm._a).apply(null,arguments)},e._OrtCreateRunOptions=function(){return(e._OrtCreateRunOptions=e.asm.$a).apply(null,arguments)},e._OrtAddRunConfigEntry=function(){return(e._OrtAddRunConfigEntry=e.asm.ab).apply(null,arguments)},e._OrtReleaseRunOptions=function(){return(e._OrtReleaseRunOptions=e.asm.bb).apply(null,arguments)},e._OrtRun=function(){return(e._OrtRun=e.asm.cb).apply(null,arguments)},e._OrtEndProfiling=function(){return(e._OrtEndProfiling=e.asm.db).apply(null,arguments)};var mt,gt=e._malloc=function(){return(gt=e._malloc=e.asm.eb).apply(null,arguments)},vt=e._free=function(){return(vt=e._free=e.asm.fb).apply(null,arguments)},wt=e._fflush=function(){return(wt=e._fflush=e.asm.gb).apply(null,arguments)},_t=e.___funcs_on_exit=function(){return(_t=e.___funcs_on_exit=e.asm.hb).apply(null,arguments)},Ot=e._setThrew=function(){return(Ot=e._setThrew=e.asm.jb).apply(null,arguments)},At=e.stackSave=function(){return(At=e.stackSave=e.asm.kb).apply(null,arguments)},St=e.stackRestore=function(){return(St=e.stackRestore=e.asm.lb).apply(null,arguments)},Tt=e.stackAlloc=function(){return(Tt=e.stackAlloc=e.asm.mb).apply(null,arguments)},Et=e.___cxa_can_catch=function(){return(Et=e.___cxa_can_catch=e.asm.nb).apply(null,arguments)},Mt=e.___cxa_is_pointer_type=function(){return(Mt=e.___cxa_is_pointer_type=e.asm.ob).apply(null,arguments)},Ct=e.dynCall_j=function(){return(Ct=e.dynCall_j=e.asm.pb).apply(null,arguments)},xt=e.dynCall_iiiiij=function(){return(xt=e.dynCall_iiiiij=e.asm.qb).apply(null,arguments)},Rt=e.dynCall_jii=function(){return(Rt=e.dynCall_jii=e.asm.rb).apply(null,arguments)},jt=e.dynCall_viiiiij=function(){return(jt=e.dynCall_viiiiij=e.asm.sb).apply(null,arguments)},kt=e.dynCall_vjji=function(){return(kt=e.dynCall_vjji=e.asm.tb).apply(null,arguments)},Dt=e.dynCall_viiijjjii=function(){return(Dt=e.dynCall_viiijjjii=e.asm.ub).apply(null,arguments)},Pt=e.dynCall_iij=function(){return(Pt=e.dynCall_iij=e.asm.vb).apply(null,arguments)},Ut=e.dynCall_ji=function(){return(Ut=e.dynCall_ji=e.asm.wb).apply(null,arguments)},Ft=e.dynCall_iiiiiij=function(){return(Ft=e.dynCall_iiiiiij=e.asm.xb).apply(null,arguments)},It=e.dynCall_iiij=function(){return(It=e.dynCall_iiij=e.asm.yb).apply(null,arguments)};function Wt(){function t(){if(!mt&&(mt=!0,e.calledRun=!0,!C)){if(Z(I),r(e),e.onRuntimeInitialized&&e.onRuntimeInitialized(),e.postRun)for("function"==typeof e.postRun&&(e.postRun=[e.postRun]);e.postRun.length;){var t=e.postRun.shift();H.unshift(t)}Z(H)}}if(!(0<B)){if(e.preRun)for("function"==typeof e.preRun&&(e.preRun=[e.preRun]);e.preRun.length;)z();Z(F),0<B||(e.setStatus?(e.setStatus("Running..."),setTimeout((function(){setTimeout((function(){e.setStatus("")}),1),t()}),1)):t())}}if(e.UTF8ToString=j,e.stringToUTF8=function(t,e,n){return k(t,T,e,n)},e.lengthBytesUTF8=D,e.stackSave=At,e.stackRestore=St,e.stackAlloc=Tt,N=function t(){mt||Wt(),mt||(N=t)},e.preInit)for("function"==typeof e.preInit&&(e.preInit=[e.preInit]);0<e.preInit.length;)e.preInit.pop()();return Wt(),t.ready});t.exports=r},967:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.iterateExtraOptions=void 0,e.iterateExtraOptions=(t,n,r,a)=>{if("object"==typeof t&&null!==t){if(r.has(t))throw new Error("Circular reference in options");r.add(t)}Object.entries(t).forEach((([t,i])=>{const o=n?n+t:t;if("object"==typeof i)(0,e.iterateExtraOptions)(i,o+".",r,a);else if("string"==typeof i||"number"==typeof i)a(o,i.toString());else{if("boolean"!=typeof i)throw new Error("Can\'t handle extra config type: "+typeof i);a(o,i?"1":"0")}}))}},586:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.setRunOptions=void 0;const r=n(967),a=n(983),i=n(361);e.setRunOptions=t=>{const e=(0,i.getInstance)();let n=0;const o=[],u=t||{};try{if(void 0===(null==t?void 0:t.logSeverityLevel))u.logSeverityLevel=2;else if("number"!=typeof t.logSeverityLevel||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if(void 0===(null==t?void 0:t.logVerbosityLevel))u.logVerbosityLevel=0;else if("number"!=typeof t.logVerbosityLevel||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);void 0===(null==t?void 0:t.terminate)&&(u.terminate=!1);let i=0;if(void 0!==(null==t?void 0:t.tag)&&(i=(0,a.allocWasmString)(t.tag,o)),n=e._OrtCreateRunOptions(u.logSeverityLevel,u.logVerbosityLevel,!!u.terminate,i),0===n)throw new Error("Can\'t create run options");return void 0!==(null==t?void 0:t.extra)&&(0,r.iterateExtraOptions)(t.extra,"",new WeakSet,((t,r)=>{const i=(0,a.allocWasmString)(t,o),u=(0,a.allocWasmString)(r,o);if(0!==e._OrtAddRunConfigEntry(n,i,u))throw new Error(`Can\'t set a run config entry: ${t} - ${r}`)})),[n,o]}catch(t){throw 0!==n&&e._OrtReleaseRunOptions(n),o.forEach(e._free),t}}},919:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.setSessionOptions=void 0;const r=n(967),a=n(983),i=n(361);e.setSessionOptions=t=>{const e=(0,i.getInstance)();let n=0;const o=[],u=t||{};(t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});const e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1")})(u);try{void 0===(null==t?void 0:t.graphOptimizationLevel)&&(u.graphOptimizationLevel="all");const c=(t=>{switch(t){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${t}`)}})(u.graphOptimizationLevel);void 0===(null==t?void 0:t.enableCpuMemArena)&&(u.enableCpuMemArena=!0),void 0===(null==t?void 0:t.enableMemPattern)&&(u.enableMemPattern=!0),void 0===(null==t?void 0:t.executionMode)&&(u.executionMode="sequential");const s=(t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}})(u.executionMode);let l=0;if(void 0!==(null==t?void 0:t.logId)&&(l=(0,a.allocWasmString)(t.logId,o)),void 0===(null==t?void 0:t.logSeverityLevel))u.logSeverityLevel=2;else if("number"!=typeof t.logSeverityLevel||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if(void 0===(null==t?void 0:t.logVerbosityLevel))u.logVerbosityLevel=0;else if("number"!=typeof t.logVerbosityLevel||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);if(void 0===(null==t?void 0:t.enableProfiling)&&(u.enableProfiling=!1),n=e._OrtCreateSessionOptions(c,!!u.enableCpuMemArena,!!u.enableMemPattern,s,!!u.enableProfiling,0,l,u.logSeverityLevel,u.logVerbosityLevel),0===n)throw new Error("Can\'t create session options");return(null==t?void 0:t.executionProviders)&&((t,e,n)=>{for(const r of e){let e="string"==typeof r?r:r.name;switch(e){case"xnnpack":e="XNNPACK";break;case"wasm":case"cpu":continue;default:throw new Error(`not supported EP: ${e}`)}const o=(0,a.allocWasmString)(e,n);if(0!==(0,i.getInstance)()._OrtAppendExecutionProvider(t,o))throw new Error(`Can\'t append execution provider: ${e}`)}})(n,t.executionProviders,o),void 0!==(null==t?void 0:t.extra)&&(0,r.iterateExtraOptions)(t.extra,"",new WeakSet,((t,r)=>{const i=(0,a.allocWasmString)(t,o),u=(0,a.allocWasmString)(r,o);if(0!==e._OrtAddSessionConfigEntry(n,i,u))throw new Error(`Can\'t set a session config entry: ${t} - ${r}`)})),[n,o]}catch(t){throw 0!==n&&e._OrtReleaseSessionOptions(n),o.forEach(e._free),t}}},983:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.allocWasmString=void 0;const r=n(361);e.allocWasmString=(t,e)=>{const n=(0,r.getInstance)(),a=n.lengthBytesUTF8(t)+1,i=n._malloc(a);return n.stringToUTF8(t,i,a),e.push(i),i}},349:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.extractTransferableBuffers=e.endProfiling=e.run=e.releaseSession=e.createSession=e.createSessionFinalize=e.createSessionAllocate=e.initOrt=void 0;const r=n(586),a=n(919),i=n(983),o=n(361);e.initOrt=(t,e)=>{const n=(0,o.getInstance)()._OrtInit(t,e);if(0!==n)throw new Error(`Can\'t initialize onnxruntime. error code = ${n}`)};const u=new Map;e.createSessionAllocate=t=>{const e=(0,o.getInstance)(),n=e._malloc(t.byteLength);return e.HEAPU8.set(t,n),[n,t.byteLength]},e.createSessionFinalize=(t,e)=>{const n=(0,o.getInstance)();let r=0,i=0,c=[];try{if([i,c]=(0,a.setSessionOptions)(e),r=n._OrtCreateSession(t[0],t[1],i),0===r)throw new Error("Can\'t create a session")}finally{n._free(t[0]),n._OrtReleaseSessionOptions(i),c.forEach(n._free)}const s=n._OrtGetInputCount(r),l=n._OrtGetOutputCount(r),f=[],p=[],h=[],d=[];for(let t=0;t<s;t++){const e=n._OrtGetInputName(r,t);if(0===e)throw new Error("Can\'t get an input name");p.push(e),f.push(n.UTF8ToString(e))}for(let t=0;t<l;t++){const e=n._OrtGetOutputName(r,t);if(0===e)throw new Error("Can\'t get an output name");d.push(e),h.push(n.UTF8ToString(e))}return u.set(r,[r,p,d]),[r,f,h]},e.createSession=(t,n)=>{const r=(0,e.createSessionAllocate)(t);return(0,e.createSessionFinalize)(r,n)},e.releaseSession=t=>{const e=(0,o.getInstance)(),n=u.get(t);if(!n)throw new Error("invalid session id");const r=n[0],a=n[1],i=n[2];a.forEach(e._OrtFree),i.forEach(e._OrtFree),e._OrtReleaseSession(r),u.delete(t)};const c=t=>{switch(t){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${t}`)}},s=t=>{switch(t){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${t}`)}},l=t=>{switch(t){case"float32":return Float32Array;case"uint8":case"bool":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}};e.run=(t,e,n,a,f)=>{const p=(0,o.getInstance)(),h=u.get(t);if(!h)throw new Error("invalid session id");const d=h[0],y=h[1],b=h[2],m=e.length,g=a.length;let v=0,w=[];const _=[],O=[];try{[v,w]=(0,r.setRunOptions)(f);for(let t=0;t<m;t++){const e=n[t][0],r=n[t][1],a=n[t][2];let o,u;if(Array.isArray(a)){u=4*a.length,o=p._malloc(u),O.push(o);let t=o/4;for(let e=0;e<a.length;e++){if("string"!=typeof a[e])throw new TypeError(`tensor data at index ${e} is not a string`);p.HEAPU32[t++]=(0,i.allocWasmString)(a[e],O)}}else u=a.byteLength,o=p._malloc(u),O.push(o),p.HEAPU8.set(new Uint8Array(a.buffer,a.byteOffset,u),o);const s=p.stackSave(),l=p.stackAlloc(4*r.length);try{let t=l/4;r.forEach((e=>p.HEAP32[t++]=e));const n=p._OrtCreateTensor(c(e),o,u,l,r.length);if(0===n)throw new Error("Can\'t create a tensor");_.push(n)}finally{p.stackRestore(s)}}const t=p.stackSave(),o=p.stackAlloc(4*m),u=p.stackAlloc(4*m),h=p.stackAlloc(4*g),A=p.stackAlloc(4*g);try{let n=o/4,r=u/4,i=h/4,c=A/4;for(let t=0;t<m;t++)p.HEAPU32[n++]=_[t],p.HEAPU32[r++]=y[e[t]];for(let t=0;t<g;t++)p.HEAPU32[i++]=0,p.HEAPU32[c++]=b[a[t]];let f=p._OrtRun(d,u,o,m,A,g,h,v);const w=[];if(0===f)for(let t=0;t<g;t++){const e=p.HEAPU32[h/4+t],n=p.stackSave(),r=p.stackAlloc(16);let a,i=0;try{if(f=p._OrtGetTensorData(e,r,r+4,r+8,r+12),0!==f)throw new Error(`Can\'t access output tensor data. error code = ${f}`);let t=r/4;const o=p.HEAPU32[t++];i=p.HEAPU32[t++];const u=p.HEAPU32[t++],c=p.HEAPU32[t++],h=[];for(let t=0;t<c;t++)h.push(p.HEAPU32[u/4+t]);p._OrtFree(u);const d=0===h.length?1:h.reduce(((t,e)=>t*e));if(a=s(o),"string"===a){const t=[];let e=i/4;for(let n=0;n<d;n++){const r=p.HEAPU32[e++],a=n===d-1?void 0:p.HEAPU32[e]-r;t.push(p.UTF8ToString(r,a))}w.push([a,h,t])}else{const t=new(l(a))(d);new Uint8Array(t.buffer,t.byteOffset,t.byteLength).set(p.HEAPU8.subarray(i,i+t.byteLength)),w.push([a,h,t])}}finally{p.stackRestore(n),"string"===a&&i&&p._free(i),p._OrtReleaseTensor(e)}}if(0===f)return w;throw new Error(`failed to call OrtRun(). error code = ${f}.`)}finally{p.stackRestore(t)}}finally{_.forEach(p._OrtReleaseTensor),O.forEach(p._free),p._OrtReleaseRunOptions(v),w.forEach(p._free)}},e.endProfiling=t=>{const e=(0,o.getInstance)(),n=u.get(t);if(!n)throw new Error("invalid session id");const r=n[0],a=e._OrtEndProfiling(r);if(0===a)throw new Error("Can\'t get an profile file name");e._OrtFree(a)},e.extractTransferableBuffers=t=>{const e=[];for(const n of t){const t=n[2];!Array.isArray(t)&&t.buffer&&e.push(t.buffer)}return e}},361:function(t,e,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n);var a=Object.getOwnPropertyDescriptor(e,n);a&&!("get"in a?!e.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,a)}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),a=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),i=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)"default"!==n&&Object.prototype.hasOwnProperty.call(t,n)&&r(e,t,n);return a(e,t),e},o=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.dispose=e.getInstance=e.initializeWebAssembly=void 0;const u=i(n(449)),c=o(n(932)),s=n(474);let l,f=!1,p=!1,h=!1;const d=(t,e)=>e?t?"ort-wasm-simd-threaded.wasm":"ort-wasm-threaded.wasm":t?"ort-wasm-simd.wasm":"ort-wasm.wasm";e.initializeWebAssembly=async t=>{if(f)return Promise.resolve();if(p)throw new Error("multiple calls to \'initializeWebAssembly()\' detected.");if(h)throw new Error("previous call to \'initializeWebAssembly()\' failed.");p=!0;const e=t.initTimeout,r=t.numThreads,a=t.simd,i=r>1&&(()=>{try{return"undefined"!=typeof SharedArrayBuffer&&("undefined"!=typeof MessageChannel&&(new MessageChannel).port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11])))}catch(t){return!1}})(),o=a&&(()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch(t){return!1}})(),y="string"==typeof t.wasmPaths?t.wasmPaths:void 0,b=d(!1,i),m=d(o,i),g="object"==typeof t.wasmPaths?t.wasmPaths[m]:void 0;let v=!1;const w=[];if(e>0&&w.push(new Promise((t=>{setTimeout((()=>{v=!0,t()}),e)}))),w.push(new Promise(((t,e)=>{const r=i?s:c.default,a={locateFile:(t,e)=>i&&t.endsWith(".worker.js")&&"undefined"!=typeof Blob?URL.createObjectURL(new Blob([n(154)],{type:"text/javascript"})):t===b?null!=g?g:(null!=y?y:e)+m:e+t};if(i)if("undefined"==typeof Blob)a.mainScriptUrlOrBlob=u.join("/","ort-wasm-threaded.js");else{const t=`var ortWasmThreaded=(function(){var _scriptDir;return ${r.toString()}})();`;a.mainScriptUrlOrBlob=new Blob([t],{type:"text/javascript"})}r(a).then((e=>{p=!1,f=!0,l=e,t()}),(t=>{p=!1,h=!0,e(t)}))}))),await Promise.race(w),v)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},e.getInstance=()=>{if(f&&l)return l;throw new Error("WebAssembly is not initialized yet.")},e.dispose=()=>{var t;!f||p||h||(p=!0,null===(t=l.PThread)||void 0===t||t.terminateAllThreads(),l=void 0,p=!1,f=!1,h=!0)}},154:t=>{"use strict";t.exports=\'"use strict";var e={},t="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node;if(t){var r=require("worker_threads"),a=r.parentPort;a.on("message",(e=>onmessage({data:e})));var o=require("fs");Object.assign(global,{self:global,require:require,Module:e,location:{href:__filename},Worker:r.Worker,importScripts:function(e){(0,eval)(o.readFileSync(e,"utf8"))},postMessage:function(e){a.postMessage(e)},performance:global.performance||{now:function(){return Date.now()}}})}var s=!1,n=[],i=function(){var e=Array.prototype.slice.call(arguments).join(" ");t?o.writeSync(2,e+"\\\\n"):console.error(e)};self.alert=function(){var t=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:t,threadId:e._pthread_self()})},e.instantiateWasm=(t,r)=>{var a=new WebAssembly.Instance(e.wasmModule,t);return r(a),e.wasmModule=null,a.exports},self.onunhandledrejection=e=>{throw e.reason??e},self.onmessage=t=>{try{if("load"===t.data.cmd){if(e.wasmModule=t.data.wasmModule,e.wasmMemory=t.data.wasmMemory,e.buffer=e.wasmMemory.buffer,e.ENVIRONMENT_IS_PTHREAD=!0,"string"==typeof t.data.urlOrBlob)importScripts(t.data.urlOrBlob);else{var r=URL.createObjectURL(t.data.urlOrBlob);importScripts(r),URL.revokeObjectURL(r)}ortWasmThreaded(e).then((function(t){e=t}))}else if("run"===t.data.cmd){e.__performance_now_clock_drift=performance.now()-t.data.time,e.__emscripten_thread_init(t.data.pthread_ptr,0,0,1),e.establishStackSpace(),e.PThread.receiveObjectTransfer(t.data),e.PThread.threadInitTLS(),s||(n.forEach((t=>{e.executeNotifiedProxyingQueue(t)})),n=[],s=!0);try{e.invokeEntryPoint(t.data.start_routine,t.data.arg)}catch(t){if("unwind"!=t){if(!(t instanceof e.ExitStatus))throw t;e.keepRuntimeAlive()||e.__emscripten_thread_exit(t.status)}}}else"cancel"===t.data.cmd?e._pthread_self()&&e.__emscripten_thread_exit(-1):"setimmediate"===t.data.target||("processProxyingQueue"===t.data.cmd?s?e.executeNotifiedProxyingQueue(t.data.queue):n.push(t.data.queue):(i("worker.js received unknown command "+t.data.cmd),i(t.data)))}catch(t){throw i("worker.js onmessage() captured an uncaught exception: "+t),t&&t.stack&&i(t.stack),e.__emscripten_thread_crashed&&e.__emscripten_thread_crashed(),t}};\\n\'},384:()=>{},993:()=>{},908:()=>{},953:()=>{},925:()=>{},449:()=>{}},e={};function n(r){var a=e[r];if(void 0!==a)return a.exports;var i=e[r]={exports:{}};return t[r].call(i.exports,i,i.exports,n),i.exports}n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),(()=>{"use strict";const t=n(349),e=n(361);self.onmessage=n=>{switch(n.data.type){case"init-wasm":(0,e.initializeWebAssembly)(n.data.in).then((()=>postMessage({type:"init-wasm"})),(t=>postMessage({type:"init-wasm",err:t})));break;case"init-ort":try{const{numThreads:e,loggingLevel:r}=n.data.in;(0,t.initOrt)(e,r),postMessage({type:"init-ort"})}catch(t){postMessage({type:"init-ort",err:t})}break;case"create_allocate":try{const{model:e}=n.data.in,r=(0,t.createSessionAllocate)(e);postMessage({type:"create_allocate",out:r})}catch(t){postMessage({type:"create_allocate",err:t})}break;case"create_finalize":try{const{modeldata:e,options:r}=n.data.in,a=(0,t.createSessionFinalize)(e,r);postMessage({type:"create_finalize",out:a})}catch(t){postMessage({type:"create_finalize",err:t})}break;case"create":try{const{model:e,options:r}=n.data.in,a=(0,t.createSession)(e,r);postMessage({type:"create",out:a})}catch(t){postMessage({type:"create",err:t})}break;case"release":try{const e=n.data.in;(0,t.releaseSession)(e),postMessage({type:"release"})}catch(t){postMessage({type:"release",err:t})}break;case"run":try{const{sessionId:e,inputIndices:r,inputs:a,outputIndices:i,options:o}=n.data.in,u=(0,t.run)(e,r,a,i,o);postMessage({type:"run",out:u},(0,t.extractTransferableBuffers)(u))}catch(t){postMessage({type:"run",err:t})}break;case"end-profiling":try{const e=n.data.in;(0,t.endProfiling)(e),postMessage({type:"end-profiling"})}catch(t){postMessage({type:"end-profiling",err:t})}}}})()})();\n', "Worker", void 0, void 0);
          }
        }, 477: (t) => {
          t.exports = function(t2, e, n, r) {
            var i2 = self || window;
            try {
              try {
                var o;
                try {
                  o = new i2.Blob([t2]);
                } catch (e2) {
                  (o = new (i2.BlobBuilder || i2.WebKitBlobBuilder || i2.MozBlobBuilder || i2.MSBlobBuilder)()).append(t2), o = o.getBlob();
                }
                var a = i2.URL || i2.webkitURL, s = a.createObjectURL(o), u = new i2[e](s, n);
                return a.revokeObjectURL(s), u;
              } catch (r2) {
                return new i2[e]("data:application/javascript,".concat(encodeURIComponent(t2)), n);
              }
            } catch (t3) {
              if (!r) throw Error("Inline worker is not supported");
              return new i2[e](r, n);
            }
          };
        }, 4154: (t) => {
          t.exports = '"use strict";var e={},t="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node;if(t){var r=require("worker_threads"),a=r.parentPort;a.on("message",(e=>onmessage({data:e})));var o=require("fs");Object.assign(global,{self:global,require:require,Module:e,location:{href:__filename},Worker:r.Worker,importScripts:function(e){(0,eval)(o.readFileSync(e,"utf8"))},postMessage:function(e){a.postMessage(e)},performance:global.performance||{now:function(){return Date.now()}}})}var s=!1,n=[],i=function(){var e=Array.prototype.slice.call(arguments).join(" ");t?o.writeSync(2,e+"\\n"):console.error(e)};self.alert=function(){var t=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:t,threadId:e._pthread_self()})},e.instantiateWasm=(t,r)=>{var a=new WebAssembly.Instance(e.wasmModule,t);return r(a),e.wasmModule=null,a.exports},self.onunhandledrejection=e=>{throw e.reason??e},self.onmessage=t=>{try{if("load"===t.data.cmd){if(e.wasmModule=t.data.wasmModule,e.wasmMemory=t.data.wasmMemory,e.buffer=e.wasmMemory.buffer,e.ENVIRONMENT_IS_PTHREAD=!0,"string"==typeof t.data.urlOrBlob)importScripts(t.data.urlOrBlob);else{var r=URL.createObjectURL(t.data.urlOrBlob);importScripts(r),URL.revokeObjectURL(r)}ortWasmThreaded(e).then((function(t){e=t}))}else if("run"===t.data.cmd){e.__performance_now_clock_drift=performance.now()-t.data.time,e.__emscripten_thread_init(t.data.pthread_ptr,0,0,1),e.establishStackSpace(),e.PThread.receiveObjectTransfer(t.data),e.PThread.threadInitTLS(),s||(n.forEach((t=>{e.executeNotifiedProxyingQueue(t)})),n=[],s=!0);try{e.invokeEntryPoint(t.data.start_routine,t.data.arg)}catch(t){if("unwind"!=t){if(!(t instanceof e.ExitStatus))throw t;e.keepRuntimeAlive()||e.__emscripten_thread_exit(t.status)}}}else"cancel"===t.data.cmd?e._pthread_self()&&e.__emscripten_thread_exit(-1):"setimmediate"===t.data.target||("processProxyingQueue"===t.data.cmd?s?e.executeNotifiedProxyingQueue(t.data.queue):n.push(t.data.queue):(i("worker.js received unknown command "+t.data.cmd),i(t.data)))}catch(t){throw i("worker.js onmessage() captured an uncaught exception: "+t),t&&t.stack&&i(t.stack),e.__emscripten_thread_crashed&&e.__emscripten_thread_crashed(),t}};\n';
        }, 1670: (t) => {
          t.exports = __WEBPACK_EXTERNAL_MODULE__1670__;
        }, 7067: () => {
        }, 1296: () => {
        }, 1384: () => {
        }, 3993: () => {
        }, 908: () => {
        }, 6953: () => {
        }, 9925: () => {
        }, 2806: () => {
        }, 6449: () => {
        }, 2850: () => {
        }, 5381: () => {
        }, 5686: (t, e, n) => {
          n.r(e), n.d(e, { flatbuffers: () => r });
          var r = {};
          r.Offset, r.Table, r.SIZEOF_SHORT = 2, r.SIZEOF_INT = 4, r.FILE_IDENTIFIER_LENGTH = 4, r.SIZE_PREFIX_LENGTH = 4, r.Encoding = { UTF8_BYTES: 1, UTF16_STRING: 2 }, r.int32 = new Int32Array(2), r.float32 = new Float32Array(r.int32.buffer), r.float64 = new Float64Array(r.int32.buffer), r.isLittleEndian = 1 === new Uint16Array(new Uint8Array([1, 0]).buffer)[0], r.Long = function(t2, e2) {
            this.low = 0 | t2, this.high = 0 | e2;
          }, r.Long.create = function(t2, e2) {
            return 0 == t2 && 0 == e2 ? r.Long.ZERO : new r.Long(t2, e2);
          }, r.Long.prototype.toFloat64 = function() {
            return (this.low >>> 0) + 4294967296 * this.high;
          }, r.Long.prototype.equals = function(t2) {
            return this.low == t2.low && this.high == t2.high;
          }, r.Long.ZERO = new r.Long(0, 0), r.Builder = function(t2) {
            if (t2) e2 = t2;
            else var e2 = 1024;
            this.bb = r.ByteBuffer.allocate(e2), this.space = e2, 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;
          }, r.Builder.prototype.clear = function() {
            this.bb.clear(), this.space = this.bb.capacity(), this.minalign = 1, this.vtable = null, this.vtable_in_use = 0, this.isNested = false, this.object_start = 0, this.vtables = [], this.vector_num_elems = 0, this.force_defaults = false;
          }, r.Builder.prototype.forceDefaults = function(t2) {
            this.force_defaults = t2;
          }, r.Builder.prototype.dataBuffer = function() {
            return this.bb;
          }, r.Builder.prototype.asUint8Array = function() {
            return this.bb.bytes().subarray(this.bb.position(), this.bb.position() + this.offset());
          }, r.Builder.prototype.prep = function(t2, e2) {
            t2 > this.minalign && (this.minalign = t2);
            for (var n2 = 1 + ~(this.bb.capacity() - this.space + e2) & t2 - 1; this.space < n2 + t2 + e2; ) {
              var i2 = this.bb.capacity();
              this.bb = r.Builder.growByteBuffer(this.bb), this.space += this.bb.capacity() - i2;
            }
            this.pad(n2);
          }, r.Builder.prototype.pad = function(t2) {
            for (var e2 = 0; e2 < t2; e2++) this.bb.writeInt8(--this.space, 0);
          }, r.Builder.prototype.writeInt8 = function(t2) {
            this.bb.writeInt8(this.space -= 1, t2);
          }, r.Builder.prototype.writeInt16 = function(t2) {
            this.bb.writeInt16(this.space -= 2, t2);
          }, r.Builder.prototype.writeInt32 = function(t2) {
            this.bb.writeInt32(this.space -= 4, t2);
          }, r.Builder.prototype.writeInt64 = function(t2) {
            this.bb.writeInt64(this.space -= 8, t2);
          }, r.Builder.prototype.writeFloat32 = function(t2) {
            this.bb.writeFloat32(this.space -= 4, t2);
          }, r.Builder.prototype.writeFloat64 = function(t2) {
            this.bb.writeFloat64(this.space -= 8, t2);
          }, r.Builder.prototype.addInt8 = function(t2) {
            this.prep(1, 0), this.writeInt8(t2);
          }, r.Builder.prototype.addInt16 = function(t2) {
            this.prep(2, 0), this.writeInt16(t2);
          }, r.Builder.prototype.addInt32 = function(t2) {
            this.prep(4, 0), this.writeInt32(t2);
          }, r.Builder.prototype.addInt64 = function(t2) {
            this.prep(8, 0), this.writeInt64(t2);
          }, r.Builder.prototype.addFloat32 = function(t2) {
            this.prep(4, 0), this.writeFloat32(t2);
          }, r.Builder.prototype.addFloat64 = function(t2) {
            this.prep(8, 0), this.writeFloat64(t2);
          }, r.Builder.prototype.addFieldInt8 = function(t2, e2, n2) {
            (this.force_defaults || e2 != n2) && (this.addInt8(e2), this.slot(t2));
          }, r.Builder.prototype.addFieldInt16 = function(t2, e2, n2) {
            (this.force_defaults || e2 != n2) && (this.addInt16(e2), this.slot(t2));
          }, r.Builder.prototype.addFieldInt32 = function(t2, e2, n2) {
            (this.force_defaults || e2 != n2) && (this.addInt32(e2), this.slot(t2));
          }, r.Builder.prototype.addFieldInt64 = function(t2, e2, n2) {
            !this.force_defaults && e2.equals(n2) || (this.addInt64(e2), this.slot(t2));
          }, r.Builder.prototype.addFieldFloat32 = function(t2, e2, n2) {
            (this.force_defaults || e2 != n2) && (this.addFloat32(e2), this.slot(t2));
          }, r.Builder.prototype.addFieldFloat64 = function(t2, e2, n2) {
            (this.force_defaults || e2 != n2) && (this.addFloat64(e2), this.slot(t2));
          }, r.Builder.prototype.addFieldOffset = function(t2, e2, n2) {
            (this.force_defaults || e2 != n2) && (this.addOffset(e2), this.slot(t2));
          }, r.Builder.prototype.addFieldStruct = function(t2, e2, n2) {
            e2 != n2 && (this.nested(e2), this.slot(t2));
          }, r.Builder.prototype.nested = function(t2) {
            if (t2 != this.offset()) throw new Error("FlatBuffers: struct must be serialized inline.");
          }, r.Builder.prototype.notNested = function() {
            if (this.isNested) throw new Error("FlatBuffers: object serialization must not be nested.");
          }, r.Builder.prototype.slot = function(t2) {
            this.vtable[t2] = this.offset();
          }, r.Builder.prototype.offset = function() {
            return this.bb.capacity() - this.space;
          }, r.Builder.growByteBuffer = function(t2) {
            var e2 = t2.capacity();
            if (3221225472 & e2) throw new Error("FlatBuffers: cannot grow buffer beyond 2 gigabytes.");
            var n2 = e2 << 1, i2 = r.ByteBuffer.allocate(n2);
            return i2.setPosition(n2 - e2), i2.bytes().set(t2.bytes(), n2 - e2), i2;
          }, r.Builder.prototype.addOffset = function(t2) {
            this.prep(r.SIZEOF_INT, 0), this.writeInt32(this.offset() - t2 + r.SIZEOF_INT);
          }, r.Builder.prototype.startObject = function(t2) {
            this.notNested(), null == this.vtable && (this.vtable = []), this.vtable_in_use = t2;
            for (var e2 = 0; e2 < t2; e2++) this.vtable[e2] = 0;
            this.isNested = true, this.object_start = this.offset();
          }, r.Builder.prototype.endObject = function() {
            if (null == this.vtable || !this.isNested) throw new Error("FlatBuffers: endObject called without startObject");
            this.addInt32(0);
            for (var t2 = this.offset(), e2 = this.vtable_in_use - 1; e2 >= 0 && 0 == this.vtable[e2]; e2--) ;
            for (var n2 = e2 + 1; e2 >= 0; e2--) this.addInt16(0 != this.vtable[e2] ? t2 - this.vtable[e2] : 0);
            this.addInt16(t2 - this.object_start);
            var i2 = (n2 + 2) * r.SIZEOF_SHORT;
            this.addInt16(i2);
            var o = 0, a = this.space;
            t: for (e2 = 0; e2 < this.vtables.length; e2++) {
              var s = this.bb.capacity() - this.vtables[e2];
              if (i2 == this.bb.readInt16(s)) {
                for (var u = r.SIZEOF_SHORT; u < i2; u += r.SIZEOF_SHORT) if (this.bb.readInt16(a + u) != this.bb.readInt16(s + u)) continue t;
                o = this.vtables[e2];
                break;
              }
            }
            return o ? (this.space = this.bb.capacity() - t2, this.bb.writeInt32(this.space, o - t2)) : (this.vtables.push(this.offset()), this.bb.writeInt32(this.bb.capacity() - t2, this.offset() - t2)), this.isNested = false, t2;
          }, r.Builder.prototype.finish = function(t2, e2, n2) {
            var i2 = n2 ? r.SIZE_PREFIX_LENGTH : 0;
            if (e2) {
              var o = e2;
              if (this.prep(this.minalign, r.SIZEOF_INT + r.FILE_IDENTIFIER_LENGTH + i2), o.length != r.FILE_IDENTIFIER_LENGTH) throw new Error("FlatBuffers: file identifier must be length " + r.FILE_IDENTIFIER_LENGTH);
              for (var a = r.FILE_IDENTIFIER_LENGTH - 1; a >= 0; a--) this.writeInt8(o.charCodeAt(a));
            }
            this.prep(this.minalign, r.SIZEOF_INT + i2), this.addOffset(t2), i2 && this.addInt32(this.bb.capacity() - this.space), this.bb.setPosition(this.space);
          }, r.Builder.prototype.finishSizePrefixed = function(t2, e2) {
            this.finish(t2, e2, true);
          }, r.Builder.prototype.requiredField = function(t2, e2) {
            var n2 = this.bb.capacity() - t2, r2 = n2 - this.bb.readInt32(n2);
            if (0 == this.bb.readInt16(r2 + e2)) throw new Error("FlatBuffers: field " + e2 + " must be set");
          }, r.Builder.prototype.startVector = function(t2, e2, n2) {
            this.notNested(), this.vector_num_elems = e2, this.prep(r.SIZEOF_INT, t2 * e2), this.prep(n2, t2 * e2);
          }, r.Builder.prototype.endVector = function() {
            return this.writeInt32(this.vector_num_elems), this.offset();
          }, r.Builder.prototype.createString = function(t2) {
            if (t2 instanceof Uint8Array) var e2 = t2;
            else {
              e2 = [];
              for (var n2 = 0; n2 < t2.length; ) {
                var r2, i2 = t2.charCodeAt(n2++);
                (r2 = i2 < 55296 || i2 >= 56320 ? i2 : (i2 << 10) + t2.charCodeAt(n2++) + -56613888) < 128 ? e2.push(r2) : (r2 < 2048 ? e2.push(r2 >> 6 & 31 | 192) : (r2 < 65536 ? e2.push(r2 >> 12 & 15 | 224) : e2.push(r2 >> 18 & 7 | 240, r2 >> 12 & 63 | 128), e2.push(r2 >> 6 & 63 | 128)), e2.push(63 & r2 | 128));
              }
            }
            this.addInt8(0), this.startVector(1, e2.length, 1), this.bb.setPosition(this.space -= e2.length), n2 = 0;
            for (var o = this.space, a = this.bb.bytes(); n2 < e2.length; n2++) a[o++] = e2[n2];
            return this.endVector();
          }, r.Builder.prototype.createLong = function(t2, e2) {
            return r.Long.create(t2, e2);
          }, r.ByteBuffer = function(t2) {
            this.bytes_ = t2, this.position_ = 0;
          }, r.ByteBuffer.allocate = function(t2) {
            return new r.ByteBuffer(new Uint8Array(t2));
          }, r.ByteBuffer.prototype.clear = function() {
            this.position_ = 0;
          }, r.ByteBuffer.prototype.bytes = function() {
            return this.bytes_;
          }, r.ByteBuffer.prototype.position = function() {
            return this.position_;
          }, r.ByteBuffer.prototype.setPosition = function(t2) {
            this.position_ = t2;
          }, r.ByteBuffer.prototype.capacity = function() {
            return this.bytes_.length;
          }, r.ByteBuffer.prototype.readInt8 = function(t2) {
            return this.readUint8(t2) << 24 >> 24;
          }, r.ByteBuffer.prototype.readUint8 = function(t2) {
            return this.bytes_[t2];
          }, r.ByteBuffer.prototype.readInt16 = function(t2) {
            return this.readUint16(t2) << 16 >> 16;
          }, r.ByteBuffer.prototype.readUint16 = function(t2) {
            return this.bytes_[t2] | this.bytes_[t2 + 1] << 8;
          }, r.ByteBuffer.prototype.readInt32 = function(t2) {
            return this.bytes_[t2] | this.bytes_[t2 + 1] << 8 | this.bytes_[t2 + 2] << 16 | this.bytes_[t2 + 3] << 24;
          }, r.ByteBuffer.prototype.readUint32 = function(t2) {
            return this.readInt32(t2) >>> 0;
          }, r.ByteBuffer.prototype.readInt64 = function(t2) {
            return new r.Long(this.readInt32(t2), this.readInt32(t2 + 4));
          }, r.ByteBuffer.prototype.readUint64 = function(t2) {
            return new r.Long(this.readUint32(t2), this.readUint32(t2 + 4));
          }, r.ByteBuffer.prototype.readFloat32 = function(t2) {
            return r.int32[0] = this.readInt32(t2), r.float32[0];
          }, r.ByteBuffer.prototype.readFloat64 = function(t2) {
            return r.int32[r.isLittleEndian ? 0 : 1] = this.readInt32(t2), r.int32[r.isLittleEndian ? 1 : 0] = this.readInt32(t2 + 4), r.float64[0];
          }, r.ByteBuffer.prototype.writeInt8 = function(t2, e2) {
            this.bytes_[t2] = e2;
          }, r.ByteBuffer.prototype.writeUint8 = function(t2, e2) {
            this.bytes_[t2] = e2;
          }, r.ByteBuffer.prototype.writeInt16 = function(t2, e2) {
            this.bytes_[t2] = e2, this.bytes_[t2 + 1] = e2 >> 8;
          }, r.ByteBuffer.prototype.writeUint16 = function(t2, e2) {
            this.bytes_[t2] = e2, this.bytes_[t2 + 1] = e2 >> 8;
          }, r.ByteBuffer.prototype.writeInt32 = function(t2, e2) {
            this.bytes_[t2] = e2, this.bytes_[t2 + 1] = e2 >> 8, this.bytes_[t2 + 2] = e2 >> 16, this.bytes_[t2 + 3] = e2 >> 24;
          }, r.ByteBuffer.prototype.writeUint32 = function(t2, e2) {
            this.bytes_[t2] = e2, this.bytes_[t2 + 1] = e2 >> 8, this.bytes_[t2 + 2] = e2 >> 16, this.bytes_[t2 + 3] = e2 >> 24;
          }, r.ByteBuffer.prototype.writeInt64 = function(t2, e2) {
            this.writeInt32(t2, e2.low), this.writeInt32(t2 + 4, e2.high);
          }, r.ByteBuffer.prototype.writeUint64 = function(t2, e2) {
            this.writeUint32(t2, e2.low), this.writeUint32(t2 + 4, e2.high);
          }, r.ByteBuffer.prototype.writeFloat32 = function(t2, e2) {
            r.float32[0] = e2, this.writeInt32(t2, r.int32[0]);
          }, r.ByteBuffer.prototype.writeFloat64 = function(t2, e2) {
            r.float64[0] = e2, this.writeInt32(t2, r.int32[r.isLittleEndian ? 0 : 1]), this.writeInt32(t2 + 4, r.int32[r.isLittleEndian ? 1 : 0]);
          }, r.ByteBuffer.prototype.getBufferIdentifier = function() {
            if (this.bytes_.length < this.position_ + r.SIZEOF_INT + r.FILE_IDENTIFIER_LENGTH) throw new Error("FlatBuffers: ByteBuffer is too short to contain an identifier.");
            for (var t2 = "", e2 = 0; e2 < r.FILE_IDENTIFIER_LENGTH; e2++) t2 += String.fromCharCode(this.readInt8(this.position_ + r.SIZEOF_INT + e2));
            return t2;
          }, r.ByteBuffer.prototype.__offset = function(t2, e2) {
            var n2 = t2 - this.readInt32(t2);
            return e2 < this.readInt16(n2) ? this.readInt16(n2 + e2) : 0;
          }, r.ByteBuffer.prototype.__union = function(t2, e2) {
            return t2.bb_pos = e2 + this.readInt32(e2), t2.bb = this, t2;
          }, r.ByteBuffer.prototype.__string = function(t2, e2) {
            t2 += this.readInt32(t2);
            var n2 = this.readInt32(t2), i2 = "", o = 0;
            if (t2 += r.SIZEOF_INT, e2 === r.Encoding.UTF8_BYTES) return this.bytes_.subarray(t2, t2 + n2);
            for (; o < n2; ) {
              var a, s = this.readUint8(t2 + o++);
              if (s < 192) a = s;
              else {
                var u = this.readUint8(t2 + o++);
                if (s < 224) a = (31 & s) << 6 | 63 & u;
                else {
                  var c = this.readUint8(t2 + o++);
                  a = s < 240 ? (15 & s) << 12 | (63 & u) << 6 | 63 & c : (7 & s) << 18 | (63 & u) << 12 | (63 & c) << 6 | 63 & this.readUint8(t2 + o++);
                }
              }
              a < 65536 ? i2 += String.fromCharCode(a) : (a -= 65536, i2 += String.fromCharCode(55296 + (a >> 10), 56320 + (1023 & a)));
            }
            return i2;
          }, r.ByteBuffer.prototype.__indirect = function(t2) {
            return t2 + this.readInt32(t2);
          }, r.ByteBuffer.prototype.__vector = function(t2) {
            return t2 + this.readInt32(t2) + r.SIZEOF_INT;
          }, r.ByteBuffer.prototype.__vector_len = function(t2) {
            return this.readInt32(t2 + this.readInt32(t2));
          }, r.ByteBuffer.prototype.__has_identifier = function(t2) {
            if (t2.length != r.FILE_IDENTIFIER_LENGTH) throw new Error("FlatBuffers: file identifier must be length " + r.FILE_IDENTIFIER_LENGTH);
            for (var e2 = 0; e2 < r.FILE_IDENTIFIER_LENGTH; e2++) if (t2.charCodeAt(e2) != this.readInt8(this.position_ + r.SIZEOF_INT + e2)) return false;
            return true;
          }, r.ByteBuffer.prototype.createLong = function(t2, e2) {
            return r.Long.create(t2, e2);
          };
        } }, __webpack_module_cache__ = {};
        function __webpack_require__(t) {
          var e = __webpack_module_cache__[t];
          if (void 0 !== e) return e.exports;
          var n = __webpack_module_cache__[t] = { exports: {} };
          return __webpack_modules__[t].call(n.exports, n, n.exports, __webpack_require__), n.exports;
        }
        __webpack_require__.n = (t) => {
          var e = t && t.__esModule ? () => t.default : () => t;
          return __webpack_require__.d(e, { a: e }), e;
        }, __webpack_require__.d = (t, e) => {
          for (var n in e) __webpack_require__.o(e, n) && !__webpack_require__.o(t, n) && Object.defineProperty(t, n, { enumerable: true, get: e[n] });
        }, __webpack_require__.g = (function() {
          if ("object" == typeof globalThis) return globalThis;
          try {
            return this || new Function("return this")();
          } catch (t) {
            if ("object" == typeof window) return window;
          }
        })(), __webpack_require__.o = (t, e) => Object.prototype.hasOwnProperty.call(t, e), __webpack_require__.r = (t) => {
          "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(t, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(t, "__esModule", { value: true });
        };
        var __webpack_exports__ = __webpack_require__(6018);
        return __webpack_exports__;
      })()));
    })(ortWeb_min$1);
    return ortWeb_min$1.exports;
  }
  var ortWeb_minExports = requireOrtWeb_min();
  const ortWeb_min = /* @__PURE__ */ getDefaultExportFromCjs$1(ortWeb_minExports);
  const ONNX_WEB = /* @__PURE__ */ _mergeNamespaces({
    __proto__: null,
    default: ortWeb_min
  }, [ortWeb_minExports]);
  let ONNX;
  const executionProviders = [
    // 'webgpu',
    "wasm"
  ];
  if (typeof process$1 !== "undefined" && ((_d = process$1 == null ? void 0 : process$1.release) == null ? void 0 : _d.name) === "node") {
    ONNX = sharp != null ? sharp : ONNX_NODE;
    executionProviders.unshift("cpu");
  } else {
    ONNX = ortWeb_min != null ? ortWeb_min : ONNX_WEB;
    const isIOS = typeof navigator !== "undefined" && /iP(hone|od|ad).+16_4.+AppleWebKit/.test(navigator.userAgent);
    if (isIOS) {
      ONNX.env.wasm.simd = false;
    }
  }
  const { env: onnx_env } = ONNX;
  const VERSION = "2.17.2";
  const WEB_CACHE_AVAILABLE = typeof self !== "undefined" && "caches" in self;
  const FS_AVAILABLE = !isEmpty(sharp);
  const PATH_AVAILABLE = !isEmpty(sharp);
  const RUNNING_LOCALLY = FS_AVAILABLE && PATH_AVAILABLE;
  const __dirname$1 = RUNNING_LOCALLY ? sharp.dirname(sharp.dirname(sharp.fileURLToPath(self.location.href))) : "./";
  const DEFAULT_CACHE_DIR = RUNNING_LOCALLY ? sharp.join(__dirname$1, "/.cache/") : null;
  const DEFAULT_LOCAL_MODEL_PATH = "/models/";
  const localModelPath = RUNNING_LOCALLY ? sharp.join(__dirname$1, DEFAULT_LOCAL_MODEL_PATH) : DEFAULT_LOCAL_MODEL_PATH;
  if (onnx_env == null ? void 0 : onnx_env.wasm) {
    onnx_env.wasm.wasmPaths = RUNNING_LOCALLY ? sharp.join(__dirname$1, "/dist/") : `https://cdn.jsdelivr.net/npm/@xenova/transformers@${VERSION}/dist/`;
  }
  const env$1 = {
    version: VERSION,
    remoteHost: "https://huggingface.co/",
    remotePathTemplate: "{model}/resolve/{revision}/",
    localModelPath,
    useFS: FS_AVAILABLE,
    /////////////////// Cache settings ///////////////////
    useBrowserCache: WEB_CACHE_AVAILABLE,
    useFSCache: FS_AVAILABLE,
    cacheDir: DEFAULT_CACHE_DIR
  };
  function isEmpty(obj) {
    return Object.keys(obj).length === 0;
  }
  class FileResponse {
    /**
     * Creates a new `FileResponse` object.
     * @param {string|URL} filePath
     */
    constructor(filePath) {
      /**
       * Mapping from file extensions to MIME types.
       */
      __publicField2(this, "_CONTENT_TYPE_MAP", {
        "txt": "text/plain",
        "html": "text/html",
        "css": "text/css",
        "js": "text/javascript",
        "json": "application/json",
        "png": "image/png",
        "jpg": "image/jpeg",
        "jpeg": "image/jpeg",
        "gif": "image/gif"
      });
      this.filePath = filePath;
      this.headers = new Headers();
      this.exists = sharp.existsSync(filePath);
      if (this.exists) {
        this.status = 200;
        this.statusText = "OK";
        let stats = sharp.statSync(filePath);
        this.headers.set("content-length", stats.size.toString());
        this.updateContentType();
        let self2 = this;
        this.body = new ReadableStream({
          start(controller) {
            self2.arrayBuffer().then((buffer2) => {
              controller.enqueue(new Uint8Array(buffer2));
              controller.close();
            });
          }
        });
      } else {
        this.status = 404;
        this.statusText = "Not Found";
        this.body = null;
      }
    }
    /**
     * Updates the 'content-type' header property of the response based on the extension of
     * the file specified by the filePath property of the current object.
     * @returns {void}
     */
    updateContentType() {
      var _a3;
      const extension = this.filePath.toString().split(".").pop().toLowerCase();
      this.headers.set("content-type", (_a3 = this._CONTENT_TYPE_MAP[extension]) != null ? _a3 : "application/octet-stream");
    }
    /**
     * Clone the current FileResponse object.
     * @returns {FileResponse} A new FileResponse object with the same properties as the current object.
     */
    clone() {
      let response = new FileResponse(this.filePath);
      response.exists = this.exists;
      response.status = this.status;
      response.statusText = this.statusText;
      response.headers = new Headers(this.headers);
      return response;
    }
    /**
     * Reads the contents of the file specified by the filePath property and returns a Promise that
     * resolves with an ArrayBuffer containing the file's contents.
     * @returns {Promise<ArrayBuffer>} A Promise that resolves with an ArrayBuffer containing the file's contents.
     * @throws {Error} If the file cannot be read.
     */
    arrayBuffer() {
      return __async(this, null, function* () {
        const data = yield sharp.promises.readFile(this.filePath);
        return data.buffer;
      });
    }
    /**
     * Reads the contents of the file specified by the filePath property and returns a Promise that
     * resolves with a Blob containing the file's contents.
     * @returns {Promise<Blob>} A Promise that resolves with a Blob containing the file's contents.
     * @throws {Error} If the file cannot be read.
     */
    blob() {
      return __async(this, null, function* () {
        const data = yield sharp.promises.readFile(this.filePath);
        return new Blob([data], { type: this.headers.get("content-type") });
      });
    }
    /**
     * Reads the contents of the file specified by the filePath property and returns a Promise that
     * resolves with a string containing the file's contents.
     * @returns {Promise<string>} A Promise that resolves with a string containing the file's contents.
     * @throws {Error} If the file cannot be read.
     */
    text() {
      return __async(this, null, function* () {
        const data = yield sharp.promises.readFile(this.filePath, "utf8");
        return data;
      });
    }
    /**
     * Reads the contents of the file specified by the filePath property and returns a Promise that
     * resolves with a parsed JavaScript object containing the file's contents.
     * 
     * @returns {Promise<Object>} A Promise that resolves with a parsed JavaScript object containing the file's contents.
     * @throws {Error} If the file cannot be read.
     */
    json() {
      return __async(this, null, function* () {
        return JSON.parse(yield this.text());
      });
    }
  }
  function isValidUrl(string2, protocols = null, validHosts = null) {
    let url2;
    try {
      url2 = new URL(string2);
    } catch (_) {
      return false;
    }
    if (protocols && !protocols.includes(url2.protocol)) {
      return false;
    }
    if (validHosts && !validHosts.includes(url2.hostname)) {
      return false;
    }
    return true;
  }
  function getFile(urlOrPath) {
    return __async(this, null, function* () {
      var _a3, _b2, _c2, _d2, _e;
      if (env$1.useFS && !isValidUrl(urlOrPath, ["http:", "https:", "blob:"])) {
        return new FileResponse(urlOrPath);
      } else if (typeof process$1 !== "undefined" && ((_a3 = process$1 == null ? void 0 : process$1.release) == null ? void 0 : _a3.name) === "node") {
        const IS_CI = !!((_b2 = process$1.env) == null ? void 0 : _b2.TESTING_REMOTELY);
        const version2 = env$1.version;
        const headers = new Headers();
        headers.set("User-Agent", `transformers.js/${version2}; is_ci/${IS_CI};`);
        const isHFURL = isValidUrl(urlOrPath, ["http:", "https:"], ["huggingface.co", "hf.co"]);
        if (isHFURL) {
          const token = (_e = (_c2 = process$1.env) == null ? void 0 : _c2.HF_TOKEN) != null ? _e : (_d2 = process$1.env) == null ? void 0 : _d2.HF_ACCESS_TOKEN;
          if (token) {
            headers.set("Authorization", `Bearer ${token}`);
          }
        }
        return fetch(urlOrPath, { headers });
      } else {
        return fetch(urlOrPath);
      }
    });
  }
  const ERROR_MAPPING = {
    // 4xx errors (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#client_error_responses)
    400: "Bad request error occurred while trying to load file",
    401: "Unauthorized access to file",
    403: "Forbidden access to file",
    404: "Could not locate file",
    408: "Request timeout error occurred while trying to load file",
    // 5xx errors (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#server_error_responses)
    500: "Internal server error error occurred while trying to load file",
    502: "Bad gateway error occurred while trying to load file",
    503: "Service unavailable error occurred while trying to load file",
    504: "Gateway timeout error occurred while trying to load file"
  };
  function handleError(status, remoteURL, fatal) {
    var _a3;
    if (!fatal) {
      return null;
    }
    const message = (_a3 = ERROR_MAPPING[status]) != null ? _a3 : `Error (${status}) occurred while trying to load file`;
    throw Error(`${message}: "${remoteURL}".`);
  }
  class FileCache {
    /**
     * Instantiate a `FileCache` object.
     * @param {string} path 
     */
    constructor(path) {
      this.path = path;
    }
    /**
     * Checks whether the given request is in the cache.
     * @param {string} request 
     * @returns {Promise<FileResponse | undefined>}
     */
    match(request) {
      return __async(this, null, function* () {
        let filePath = sharp.join(this.path, request);
        let file2 = new FileResponse(filePath);
        if (file2.exists) {
          return file2;
        } else {
          return void 0;
        }
      });
    }
    /**
     * Adds the given response to the cache.
     * @param {string} request 
     * @param {Response|FileResponse} response 
     * @returns {Promise<void>}
     */
    put(request, response) {
      return __async(this, null, function* () {
        const buffer2 = Buffer.from(yield response.arrayBuffer());
        let outputPath = sharp.join(this.path, request);
        try {
          yield sharp.promises.mkdir(sharp.dirname(outputPath), { recursive: true });
          yield sharp.promises.writeFile(outputPath, buffer2);
        } catch (err) {
          console.warn("An error occurred while writing the file to cache:", err);
        }
      });
    }
    // TODO add the rest?
    // addAll(requests: RequestInfo[]): Promise<void>;
    // delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise<boolean>;
    // keys(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise<ReadonlyArray<Request>>;
    // match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise<Response | undefined>;
    // matchAll(request?: RequestInfo | URL, options?: CacheQueryOptions): Promise<ReadonlyArray<Response>>;
  }
  function tryCache(cache, ...names2) {
    return __async(this, null, function* () {
      for (let name2 of names2) {
        try {
          let result2 = yield cache.match(name2);
          if (result2) return result2;
        } catch (e) {
          continue;
        }
      }
      return void 0;
    });
  }
  function getModelFile(_0, _1) {
    return __async(this, arguments, function* (path_or_repo_id, filename, fatal = true, options = {}) {
      var _a3, _b2;
      dispatchCallback(options.progress_callback, {
        status: "initiate",
        name: path_or_repo_id,
        file: filename
      });
      let cache;
      if (!cache && env$1.useBrowserCache) {
        if (typeof caches === "undefined") {
          throw Error("Browser cache is not available in this environment.");
        }
        try {
          cache = yield caches.open("transformers-cache");
        } catch (e) {
          console.warn("An error occurred while opening the browser cache:", e);
        }
      }
      if (!cache && env$1.useFSCache) {
        cache = new FileCache((_a3 = options.cache_dir) != null ? _a3 : env$1.cacheDir);
      }
      const revision = (_b2 = options.revision) != null ? _b2 : "main";
      let requestURL = pathJoin(path_or_repo_id, filename);
      let localPath = pathJoin(env$1.localModelPath, requestURL);
      let remoteURL = pathJoin(
        env$1.remoteHost,
        env$1.remotePathTemplate.replaceAll("{model}", path_or_repo_id).replaceAll("{revision}", encodeURIComponent(revision)),
        filename
      );
      let fsCacheKey = revision === "main" ? requestURL : pathJoin(path_or_repo_id, revision, filename);
      let cacheKey;
      let proposedCacheKey = cache instanceof FileCache ? fsCacheKey : remoteURL;
      let toCacheResponse = false;
      let response;
      if (cache) {
        response = yield tryCache(cache, localPath, proposedCacheKey);
      }
      const cacheHit = response !== void 0;
      if (response === void 0) {
        {
          const isURL = isValidUrl(requestURL, ["http:", "https:"]);
          if (!isURL) {
            try {
              response = yield getFile(localPath);
              cacheKey = localPath;
            } catch (e) {
              console.warn(`Unable to load from local path "${localPath}": "${e}"`);
            }
          } else if (options.local_files_only) {
            throw new Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${requestURL}.`);
          } else ;
        }
        if (response === void 0 || response.status === 404) {
          if (options.local_files_only || false) {
            if (fatal) {
              throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${localPath}".`);
            } else {
              return null;
            }
          }
          response = yield getFile(remoteURL);
          if (response.status !== 200) {
            return handleError(response.status, remoteURL, fatal);
          }
          cacheKey = proposedCacheKey;
        }
        toCacheResponse = cache && typeof Response !== "undefined" && response instanceof Response && response.status === 200;
      }
      dispatchCallback(options.progress_callback, {
        status: "download",
        name: path_or_repo_id,
        file: filename
      });
      const progressInfo = {
        status: "progress",
        name: path_or_repo_id,
        file: filename
      };
      let buffer2;
      if (!options.progress_callback) {
        buffer2 = new Uint8Array(yield response.arrayBuffer());
      } else if (cacheHit && typeof navigator !== "undefined" && /firefox/i.test(navigator.userAgent)) {
        buffer2 = new Uint8Array(yield response.arrayBuffer());
        dispatchCallback(options.progress_callback, __spreadProps(__spreadValues({}, progressInfo), {
          progress: 100,
          loaded: buffer2.length,
          total: buffer2.length
        }));
      } else {
        buffer2 = yield readResponse(response, (data) => {
          dispatchCallback(options.progress_callback, __spreadValues(__spreadValues({}, progressInfo), data));
        });
      }
      if (
        // Only cache web responses
        // i.e., do not cache FileResponses (prevents duplication)
        toCacheResponse && cacheKey && // Check again whether request is in cache. If not, we add the response to the cache
        (yield cache.match(cacheKey)) === void 0
      ) {
        yield cache.put(cacheKey, new Response(buffer2, {
          headers: response.headers
        })).catch((err) => {
          console.warn(`Unable to add response to browser cache: ${err}.`);
        });
      }
      dispatchCallback(options.progress_callback, {
        status: "done",
        name: path_or_repo_id,
        file: filename
      });
      return buffer2;
    });
  }
  function getModelJSON(_0, _1) {
    return __async(this, arguments, function* (modelPath, fileName, fatal = true, options = {}) {
      let buffer2 = yield getModelFile(modelPath, fileName, fatal, options);
      if (buffer2 === null) {
        return {};
      }
      let decoder = new TextDecoder("utf-8");
      let jsonData = decoder.decode(buffer2);
      return JSON.parse(jsonData);
    });
  }
  function readResponse(response, progress_callback) {
    return __async(this, null, function* () {
      const contentLength = response.headers.get("Content-Length");
      if (contentLength === null) {
        console.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");
      }
      let total = parseInt(contentLength != null ? contentLength : "0");
      let buffer2 = new Uint8Array(total);
      let loaded = 0;
      const reader = response.body.getReader();
      function read() {
        return __async(this, null, function* () {
          const { done, value } = yield reader.read();
          if (done) return;
          let newLoaded = loaded + value.length;
          if (newLoaded > total) {
            total = newLoaded;
            let newBuffer = new Uint8Array(total);
            newBuffer.set(buffer2);
            buffer2 = newBuffer;
          }
          buffer2.set(value, loaded);
          loaded = newLoaded;
          const progress = loaded / total * 100;
          progress_callback({
            progress,
            loaded,
            total
          });
          return read();
        });
      }
      yield read();
      return buffer2;
    });
  }
  function pathJoin(...parts) {
    parts = parts.map((part, index2) => {
      if (index2) {
        part = part.replace(new RegExp("^/"), "");
      }
      if (index2 !== parts.length - 1) {
        part = part.replace(new RegExp("/$"), "");
      }
      return part;
    });
    return parts.join("/");
  }
  function permute_data(array2, dims, axes) {
    const shape = new Array(axes.length);
    const stride = new Array(axes.length);
    for (let i2 = axes.length - 1, s = 1; i2 >= 0; --i2) {
      stride[i2] = s;
      shape[i2] = dims[axes[i2]];
      s *= shape[i2];
    }
    const invStride = axes.map((_, i2) => stride[axes.indexOf(i2)]);
    const permutedData = new array2.constructor(array2.length);
    for (let i2 = 0; i2 < array2.length; ++i2) {
      let newIndex = 0;
      for (let j = dims.length - 1, k = i2; j >= 0; --j) {
        newIndex += k % dims[j] * invStride[j];
        k = Math.floor(k / dims[j]);
      }
      permutedData[newIndex] = array2[i2];
    }
    return [permutedData, shape];
  }
  function softmax(arr) {
    const maxVal = max(arr)[0];
    const exps = arr.map((x) => Math.exp(x - maxVal));
    const sumExps = exps.reduce((acc, val) => acc + val, 0);
    const softmaxArr = exps.map((x) => x / sumExps);
    return (
      /** @type {T} */
      softmaxArr
    );
  }
  function log_softmax(arr) {
    const softmaxArr = softmax(arr);
    const logSoftmaxArr = softmaxArr.map((x) => Math.log(x));
    return (
      /** @type {T} */
      logSoftmaxArr
    );
  }
  function getTopItems(items2, top_k = 0) {
    items2 = Array.from(items2).map((x, i2) => [i2, x]).sort((a, b) => b[1] - a[1]);
    if (top_k !== null && top_k > 0) {
      items2 = items2.slice(0, top_k);
    }
    return items2;
  }
  function max(arr) {
    if (arr.length === 0) throw Error("Array must not be empty");
    let max2 = arr[0];
    let indexOfMax = 0;
    for (let i2 = 1; i2 < arr.length; ++i2) {
      if (arr[i2] > max2) {
        max2 = arr[i2];
        indexOfMax = i2;
      }
    }
    return [Number(max2), indexOfMax];
  }
  function medianFilter(data, windowSize) {
    if (windowSize % 2 === 0 || windowSize <= 0) {
      throw new Error("Window size must be a positive odd number");
    }
    const outputArray = new data.constructor(data.length);
    const buffer2 = new data.constructor(windowSize);
    const halfWindowSize = Math.floor(windowSize / 2);
    for (let i2 = 0; i2 < data.length; ++i2) {
      let valuesIndex = 0;
      for (let j = -halfWindowSize; j <= halfWindowSize; ++j) {
        let index2 = i2 + j;
        if (index2 < 0) {
          index2 = Math.abs(index2);
        } else if (index2 >= data.length) {
          index2 = 2 * (data.length - 1) - index2;
        }
        buffer2[valuesIndex++] = data[index2];
      }
      buffer2.sort();
      outputArray[i2] = buffer2[halfWindowSize];
    }
    return outputArray;
  }
  const DataTypeMap = Object.freeze({
    float32: Float32Array,
    float64: Float64Array,
    string: Array,
    // string[]
    int8: Int8Array,
    uint8: Uint8Array,
    int16: Int16Array,
    uint16: Uint16Array,
    int32: Int32Array,
    uint32: Uint32Array,
    int64: BigInt64Array,
    uint64: BigUint64Array,
    bool: Uint8Array
  });
  const ONNXTensor$1 = ONNX.Tensor;
  class Tensor {
    /**
     * Create a new Tensor or copy an existing Tensor.
     * @param {[DataType, DataArray, number[]]|[import('onnxruntime-common').Tensor]} args
     */
    constructor(...args) {
      /** @type {number[]} Dimensions of the tensor. */
      __publicField2(this, "dims");
      /** @type {DataType} Type of the tensor. */
      __publicField2(this, "type");
      /** @type {DataArray} The data stored in the tensor. */
      __publicField2(this, "data");
      /** @type {number} The number of elements in the tensor. */
      __publicField2(this, "size");
      if (args[0] instanceof ONNXTensor$1) {
        Object.assign(this, args[0]);
      } else {
        Object.assign(this, new ONNXTensor$1(
          /** @type {DataType} */
          args[0],
          /** @type {Exclude<import('./maths.js').AnyTypedArray, Uint8ClampedArray>} */
          args[1],
          args[2]
        ));
      }
      return new Proxy(this, {
        get: (obj, key) => {
          if (typeof key === "string") {
            let index2 = Number(key);
            if (Number.isInteger(index2)) {
              return obj._getitem(index2);
            }
          }
          return obj[key];
        },
        set: (obj, key, value) => {
          return obj[key] = value;
        }
      });
    }
    /**
     * Returns an iterator object for iterating over the tensor data in row-major order.
     * If the tensor has more than one dimension, the iterator will yield subarrays.
     * @returns {Iterator} An iterator object for iterating over the tensor data in row-major order.
     */
    *[Symbol.iterator]() {
      const [iterLength, ...iterDims] = this.dims;
      if (iterDims.length > 0) {
        const iterSize = iterDims.reduce((a, b) => a * b);
        for (let i2 = 0; i2 < iterLength; ++i2) {
          yield this._subarray(i2, iterSize, iterDims);
        }
      } else {
        yield* __yieldStar(this.data);
      }
    }
    /**
     * Index into a Tensor object.
     * @param {number} index The index to access.
     * @returns {Tensor} The data at the specified index.
     */
    _getitem(index2) {
      const [iterLength, ...iterDims] = this.dims;
      index2 = safeIndex(index2, iterLength);
      if (iterDims.length > 0) {
        const iterSize = iterDims.reduce((a, b) => a * b);
        return this._subarray(index2, iterSize, iterDims);
      } else {
        return new Tensor(this.type, [this.data[index2]], iterDims);
      }
    }
    /**
     * @param {number|bigint} item The item to search for in the tensor
     * @returns {number} The index of the first occurrence of item in the tensor data.
     */
    indexOf(item) {
      for (let index2 = 0; index2 < this.data.length; ++index2) {
        if (this.data[index2] == item) {
          return index2;
        }
      }
      return -1;
    }
    /**
     * @param {number} index 
     * @param {number} iterSize 
     * @param {any} iterDims 
     * @returns {Tensor}
     */
    _subarray(index2, iterSize, iterDims) {
      const o1 = index2 * iterSize;
      const o2 = (index2 + 1) * iterSize;
      const data = "subarray" in this.data ? this.data.subarray(o1, o2) : this.data.slice(o1, o2);
      return new Tensor(this.type, data, iterDims);
    }
    /**
     * Returns the value of this tensor as a standard JavaScript Number. This only works
     * for tensors with one element. For other cases, see `Tensor.tolist()`.
     * @returns {number|bigint} The value of this tensor as a standard JavaScript Number.
     * @throws {Error} If the tensor has more than one element.
     */
    item() {
      if (this.data.length !== 1) {
        throw new Error(`a Tensor with ${this.data.length} elements cannot be converted to Scalar`);
      }
      return this.data[0];
    }
    /**
     * Convert tensor data to a n-dimensional JS list
     * @returns {Array}
     */
    tolist() {
      return reshape(this.data, this.dims);
    }
    /**
     * Return a new Tensor with the sigmoid function applied to each element.
     * @returns {Tensor} The tensor with the sigmoid function applied.
     */
    sigmoid() {
      return this.clone().sigmoid_();
    }
    /**
     * Applies the sigmoid function to the tensor in place.
     * @returns {Tensor} Returns `this`.
     */
    sigmoid_() {
      for (let i2 = 0; i2 < this.data.length; ++i2) {
        this.data[i2] = 1 / (1 + Math.exp(-this.data[i2]));
      }
      return this;
    }
    /**
     * Return a new Tensor with every element multiplied by a constant.
     * @param {number} val The value to multiply by.
     * @returns {Tensor} The new tensor.
     */
    mul(val) {
      return this.clone().mul_(val);
    }
    /**
     * Multiply the tensor by a constant in place.
     * @param {number} val The value to multiply by.
     * @returns {Tensor} Returns `this`.
     */
    mul_(val) {
      for (let i2 = 0; i2 < this.data.length; ++i2) {
        this.data[i2] *= val;
      }
      return this;
    }
    /**
     * Return a new Tensor with every element added by a constant.
     * @param {number} val The value to add by.
     * @returns {Tensor} The new tensor.
     */
    add(val) {
      return this.clone().add_(val);
    }
    /**
     * Add the tensor by a constant in place.
     * @param {number} val The value to add by.
     * @returns {Tensor} Returns `this`.
     */
    add_(val) {
      for (let i2 = 0; i2 < this.data.length; ++i2) {
        this.data[i2] += val;
      }
      return this;
    }
    clone() {
      return new Tensor(this.type, this.data.slice(), this.dims.slice());
    }
    slice(...slices) {
      let newTensorDims = [];
      let newOffsets = [];
      for (let sliceIndex = 0; sliceIndex < this.dims.length; ++sliceIndex) {
        let slice = slices[sliceIndex];
        if (slice === null || slice === void 0) {
          newOffsets.push([0, this.dims[sliceIndex]]);
          newTensorDims.push(this.dims[sliceIndex]);
        } else if (typeof slice === "number") {
          slice = safeIndex(slice, this.dims[sliceIndex], sliceIndex);
          newOffsets.push([slice, slice + 1]);
        } else if (Array.isArray(slice) && slice.length === 2) {
          if (slice[0] > slice[1]) {
            throw new Error(`Invalid slice: ${slice}`);
          }
          let offsets = [
            Math.max(slice[0], 0),
            Math.min(slice[1], this.dims[sliceIndex])
          ];
          newOffsets.push(offsets);
          newTensorDims.push(offsets[1] - offsets[0]);
        } else {
          throw new Error(`Invalid slice: ${slice}`);
        }
      }
      let newDims = newOffsets.map(([start, end]) => end - start);
      let newBufferSize = newDims.reduce((a, b) => a * b);
      let data = new this.data.constructor(newBufferSize);
      const stride = this.stride();
      for (let i2 = 0; i2 < newBufferSize; ++i2) {
        let originalIndex = 0;
        for (let j = newDims.length - 1, num = i2; j >= 0; --j) {
          const size = newDims[j];
          originalIndex += (num % size + newOffsets[j][0]) * stride[j];
          num = Math.floor(num / size);
        }
        data[i2] = this.data[originalIndex];
      }
      return new Tensor(this.type, data, newTensorDims);
    }
    /**
     * Return a permuted version of this Tensor, according to the provided dimensions.
     * @param  {...number} dims Dimensions to permute.
     * @returns {Tensor} The permuted tensor.
     */
    permute(...dims) {
      return permute(this, dims);
    }
    // TODO: implement transpose. For now (backwards compatibility), it's just an alias for permute()
    transpose(...dims) {
      return this.permute(...dims);
    }
    // TODO add .max() and .min() methods
    /**
     * Returns the sum of each row of the input tensor in the given dimension dim.
     * 
     * @param {number} [dim=null] The dimension or dimensions to reduce. If `null`, all dimensions are reduced.
     * @param {boolean} keepdim Whether the output tensor has `dim` retained or not.
     * @returns The summed tensor
     */
    sum(dim = null, keepdim = false) {
      return this.norm(1, dim, keepdim);
    }
    /**
     * Returns the matrix norm or vector norm of a given tensor.
     * @param {number|string} [p='fro'] The order of norm
     * @param {number} [dim=null] Specifies which dimension of the tensor to calculate the norm across.
     * If dim is None, the norm will be calculated across all dimensions of input.
     * @param {boolean} [keepdim=false] Whether the output tensors have dim retained or not.
     * @returns {Tensor} The norm of the tensor.
     */
    norm(p = "fro", dim = null, keepdim = false) {
      if (p === "fro") {
        p = 2;
      } else if (typeof p === "string") {
        throw Error(`Unsupported norm: ${p}`);
      }
      if (dim === null) {
        let val = __pow(this.data.reduce((a, b) => a + __pow(b, p), 0), 1 / p);
        return new Tensor(this.type, [val], []);
      }
      dim = safeIndex(dim, this.dims.length);
      const resultDims = this.dims.slice();
      resultDims[dim] = 1;
      const result2 = new this.data.constructor(this.data.length / this.dims[dim]);
      for (let i2 = 0; i2 < this.data.length; ++i2) {
        let resultIndex = 0;
        for (let j = this.dims.length - 1, num = i2, resultMultiplier = 1; j >= 0; --j) {
          const size = this.dims[j];
          if (j !== dim) {
            const index2 = num % size;
            resultIndex += index2 * resultMultiplier;
            resultMultiplier *= resultDims[j];
          }
          num = Math.floor(num / size);
        }
        result2[resultIndex] += __pow(this.data[i2], p);
      }
      if (p !== 1) {
        for (let i2 = 0; i2 < result2.length; ++i2) {
          result2[i2] = __pow(result2[i2], 1 / p);
        }
      }
      if (!keepdim) {
        resultDims.splice(dim, 1);
      }
      return new Tensor(this.type, result2, resultDims);
    }
    /**
     * Performs `L_p` normalization of inputs over specified dimension. Operates in place.
     * @param {number} [p=2] The exponent value in the norm formulation
     * @param {number} [dim=1] The dimension to reduce
     * @returns {Tensor} `this` for operation chaining.
     */
    normalize_(p = 2, dim = 1) {
      dim = safeIndex(dim, this.dims.length);
      const norm = this.norm(p, dim, true);
      for (let i2 = 0; i2 < this.data.length; ++i2) {
        let resultIndex = 0;
        for (let j = this.dims.length - 1, num = i2, resultMultiplier = 1; j >= 0; --j) {
          const size = this.dims[j];
          if (j !== dim) {
            const index2 = num % size;
            resultIndex += index2 * resultMultiplier;
            resultMultiplier *= this.dims[j];
          }
          num = Math.floor(num / size);
        }
        this.data[i2] /= norm.data[resultIndex];
      }
      return this;
    }
    /**
     * Performs `L_p` normalization of inputs over specified dimension.
     * @param {number} [p=2] The exponent value in the norm formulation
     * @param {number} [dim=1] The dimension to reduce
     * @returns {Tensor} The normalized tensor.
     */
    normalize(p = 2, dim = 1) {
      return this.clone().normalize_(p, dim);
    }
    /**
     * Compute and return the stride of this tensor.
     * Stride is the jump necessary to go from one element to the next one in the specified dimension dim.
     * @returns {number[]} The stride of this tensor.
     */
    stride() {
      return dimsToStride(this.dims);
    }
    /**
     * Returns a tensor with all specified dimensions of input of size 1 removed.
     * 
     * NOTE: The returned tensor shares the storage with the input tensor, so changing the contents of one will change the contents of the other.
     * If you would like a copy, use `tensor.clone()` before squeezing.
     * 
     * @param {number} [dim=null] If given, the input will be squeezed only in the specified dimensions.
     * @returns The squeezed tensor
     */
    squeeze(dim = null) {
      return new Tensor(
        this.type,
        this.data,
        calc_squeeze_dims(this.dims, dim)
      );
    }
    /**
     * In-place version of @see {@link Tensor.squeeze}
     */
    squeeze_(dim = null) {
      this.dims = calc_squeeze_dims(this.dims, dim);
      return this;
    }
    /**
     * Returns a new tensor with a dimension of size one inserted at the specified position.
     * 
     * NOTE: The returned tensor shares the same underlying data with this tensor.
     * 
     * @param {number} dim The index at which to insert the singleton dimension
     * @returns The unsqueezed tensor
     */
    unsqueeze(dim = null) {
      return new Tensor(
        this.type,
        this.data,
        calc_unsqueeze_dims(this.dims, dim)
      );
    }
    /**
     * In-place version of @see {@link Tensor.unsqueeze}
     */
    unsqueeze_(dim = null) {
      this.dims = calc_unsqueeze_dims(this.dims, dim);
      return this;
    }
    /**
     * In-place version of @see {@link Tensor.flatten}
     */
    flatten_(start_dim = 0, end_dim = -1) {
      end_dim = (end_dim + this.dims.length) % this.dims.length;
      let dimsToKeepBefore = this.dims.slice(0, start_dim);
      let dimsToFlatten = this.dims.slice(start_dim, end_dim + 1);
      let dimsToKeepAfter = this.dims.slice(end_dim + 1);
      this.dims = [...dimsToKeepBefore, dimsToFlatten.reduce((a, b) => a * b, 1), ...dimsToKeepAfter];
      return this;
    }
    /**
     * Flattens input by reshaping it into a one-dimensional tensor.
     * If `start_dim` or `end_dim` are passed, only dimensions starting with `start_dim`
     * and ending with `end_dim` are flattened. The order of elements in input is unchanged.
     * @param {number} start_dim the first dim to flatten
     * @param {number} end_dim the last dim to flatten
     * @returns The flattened tensor.
     */
    flatten(start_dim = 0, end_dim = -1) {
      return this.clone().flatten_(start_dim, end_dim);
    }
    /**
     * Returns a new tensor with the same data as the `self` tensor but of a different `shape`.
     * @param  {...number} dims the desired size
     * @returns {Tensor} The tensor with the same data but different shape
     */
    view(...dims) {
      let inferredIndex = -1;
      for (let i2 = 0; i2 < dims.length; ++i2) {
        if (dims[i2] === -1) {
          if (inferredIndex !== -1) {
            throw new Error("Only one dimension can be inferred");
          }
          inferredIndex = i2;
        }
      }
      if (inferredIndex !== -1) {
        const productOther = dims.reduce((product, curr, index2) => {
          return index2 !== inferredIndex ? product * curr : product;
        }, 1);
        dims[inferredIndex] = this.data.length / productOther;
      }
      return new Tensor(this.type, this.data, dims);
    }
    neg_() {
      for (let i2 = 0; i2 < this.data.length; ++i2) {
        this.data[i2] = -this.data[i2];
      }
      return this;
    }
    neg() {
      return this.clone().neg_();
    }
    /**
     * In-place version of @see {@link Tensor.clamp}
     */
    clamp_(min, max2) {
      for (let i2 = 0; i2 < this.data.length; ++i2) {
        this.data[i2] = Math.min(Math.max(this.data[i2], min), max2);
      }
      return this;
    }
    /**
     * Clamps all elements in input into the range [ min, max ]
     * @param {number} min lower-bound of the range to be clamped to
     * @param {number} max upper-bound of the range to be clamped to
     * @returns the output tensor.
     */
    clamp(min, max2) {
      return this.clone().clamp_(min, max2);
    }
    /**
     * In-place version of @see {@link Tensor.round}
     */
    round_() {
      for (let i2 = 0; i2 < this.data.length; ++i2) {
        this.data[i2] = Math.round(this.data[i2]);
      }
      return this;
    }
    /**
     * Rounds elements of input to the nearest integer.
     * @returns the output tensor.
     */
    round() {
      return this.clone().round_();
    }
    /**
     * Performs Tensor dtype conversion.
     * @param {DataType} type The desired data type.
     * @returns {Tensor} The converted tensor.
     */
    to(type2) {
      if (this.type === type2) return this;
      if (!DataTypeMap.hasOwnProperty(type2)) {
        throw new Error(`Unsupported type: ${type2}`);
      }
      return new Tensor(type2, DataTypeMap[type2].from(this.data), this.dims);
    }
  }
  function reshape(data, dimensions) {
    const totalElements = data.length;
    const dimensionSize = dimensions.reduce((a, b) => a * b);
    if (totalElements !== dimensionSize) {
      throw Error(`cannot reshape array of size ${totalElements} into shape (${dimensions})`);
    }
    let reshapedArray = data;
    for (let i2 = dimensions.length - 1; i2 >= 0; i2--) {
      reshapedArray = reshapedArray.reduce((acc, val) => {
        let lastArray = acc[acc.length - 1];
        if (lastArray.length < dimensions[i2]) {
          lastArray.push(val);
        } else {
          acc.push([val]);
        }
        return acc;
      }, [[]]);
    }
    return reshapedArray[0];
  }
  function permute(tensor, axes) {
    const [permutedData, shape] = permute_data(tensor.data, tensor.dims, axes);
    return new Tensor(tensor.type, permutedData, shape);
  }
  function calc_squeeze_dims(dims, dim) {
    dims = dims.slice();
    if (dim === null) {
      dims = dims.filter((d) => d !== 1);
    } else if (typeof dim === "number") {
      if (dims[dim] === 1) {
        dims.splice(dim, 1);
      }
    } else if (Array.isArray(dim)) {
      dims = dims.filter((x, i2) => {
        return x !== 1 || !dim.includes(i2);
      });
    }
    return dims;
  }
  function calc_unsqueeze_dims(dims, dim) {
    dim = safeIndex(dim, dims.length + 1);
    dims = dims.slice();
    dims.splice(dim, 0, 1);
    return dims;
  }
  function safeIndex(index2, size, dimension = null) {
    if (index2 < -size || index2 >= size) {
      throw new Error(`IndexError: index ${index2} is out of bounds for dimension${dimension === null ? "" : " " + dimension} with size ${size}`);
    }
    if (index2 < 0) {
      index2 = (index2 % size + size) % size;
    }
    return index2;
  }
  function cat(tensors, dim = 0) {
    dim = safeIndex(dim, tensors[0].dims.length);
    const resultDims = tensors[0].dims.slice();
    resultDims[dim] = tensors.reduce((a, b) => a + b.dims[dim], 0);
    const resultSize = resultDims.reduce((a, b) => a * b, 1);
    const result2 = new tensors[0].data.constructor(resultSize);
    const resultType = tensors[0].type;
    if (dim === 0) {
      let offset = 0;
      for (let t of tensors) {
        result2.set(t.data, offset);
        offset += t.data.length;
      }
    } else {
      let currentDim = 0;
      for (let t = 0; t < tensors.length; ++t) {
        let tensor = tensors[t];
        for (let i2 = 0; i2 < tensor.data.length; ++i2) {
          let resultIndex = 0;
          for (let j = tensor.dims.length - 1, num = i2, resultMultiplier = 1; j >= 0; --j) {
            const size = tensor.dims[j];
            let index2 = num % size;
            if (j === dim) {
              index2 += currentDim;
            }
            resultIndex += index2 * resultMultiplier;
            resultMultiplier *= resultDims[j];
            num = Math.floor(num / size);
          }
          result2[resultIndex] = tensor.data[i2];
        }
        currentDim += tensor.dims[dim];
      }
    }
    return new Tensor(resultType, result2, resultDims);
  }
  function stack(tensors, dim = 0) {
    return cat(tensors.map((t) => t.unsqueeze(dim)), dim);
  }
  function std_mean(input, dim = null, correction = 1, keepdim = false) {
    if (dim === null) {
      const sum = input.data.reduce((a, b) => a + b, 0);
      const mean2 = sum / input.data.length;
      const std = Math.sqrt(input.data.reduce((a, b) => a + __pow(b - mean2, 2), 0) / (input.data.length - correction));
      const meanTensor2 = new Tensor(input.type, [mean2], [
        /* scalar */
      ]);
      const stdTensor2 = new Tensor(input.type, [std], [
        /* scalar */
      ]);
      return [stdTensor2, meanTensor2];
    }
    dim = safeIndex(dim, input.dims.length);
    const meanTensor = mean(input, dim, keepdim);
    const resultDims = input.dims.slice();
    resultDims[dim] = 1;
    const result2 = new input.data.constructor(input.data.length / input.dims[dim]);
    for (let i2 = 0; i2 < input.data.length; ++i2) {
      let resultIndex = 0;
      for (let j = input.dims.length - 1, num = i2, resultMultiplier = 1; j >= 0; --j) {
        const size = input.dims[j];
        if (j !== dim) {
          const index2 = num % size;
          resultIndex += index2 * resultMultiplier;
          resultMultiplier *= resultDims[j];
        }
        num = Math.floor(num / size);
      }
      result2[resultIndex] += __pow(input.data[i2] - meanTensor.data[resultIndex], 2);
    }
    for (let i2 = 0; i2 < result2.length; ++i2) {
      result2[i2] = Math.sqrt(result2[i2] / (input.dims[dim] - correction));
    }
    if (!keepdim) {
      resultDims.splice(dim, 1);
    }
    const stdTensor = new Tensor(input.type, result2, resultDims);
    return [stdTensor, meanTensor];
  }
  function mean(input, dim = null, keepdim = false) {
    if (dim === null) {
      let val = input.data.reduce((a, b) => a + b, 0);
      return new Tensor(input.type, [val / input.data.length], [
        /* scalar */
      ]);
    }
    dim = safeIndex(dim, input.dims.length);
    const resultDims = input.dims.slice();
    resultDims[dim] = 1;
    const result2 = new input.data.constructor(input.data.length / input.dims[dim]);
    for (let i2 = 0; i2 < input.data.length; ++i2) {
      let resultIndex = 0;
      for (let j = input.dims.length - 1, num = i2, resultMultiplier = 1; j >= 0; --j) {
        const size = input.dims[j];
        if (j !== dim) {
          const index2 = num % size;
          resultIndex += index2 * resultMultiplier;
          resultMultiplier *= resultDims[j];
        }
        num = Math.floor(num / size);
      }
      result2[resultIndex] += input.data[i2];
    }
    if (input.dims[dim] !== 1) {
      for (let i2 = 0; i2 < result2.length; ++i2) {
        result2[i2] = result2[i2] / input.dims[dim];
      }
    }
    if (!keepdim) {
      resultDims.splice(dim, 1);
    }
    return new Tensor(input.type, result2, resultDims);
  }
  function dynamicTimeWarping(matrix) {
    const [output_length, input_length] = matrix.dims;
    const outputShape = [output_length + 1, input_length + 1];
    const cost = new Tensor(
      "float32",
      new Float32Array(outputShape[0] * outputShape[1]).fill(Infinity),
      outputShape
    );
    const trace = new Tensor(
      "float32",
      new Float32Array(outputShape[0] * outputShape[1]).fill(-1),
      outputShape
    );
    cost[0].data[0] = 0;
    for (let j2 = 1; j2 < input_length + 1; ++j2) {
      for (let i3 = 1; i3 < output_length + 1; ++i3) {
        const c0 = cost[i3 - 1][j2 - 1].item();
        const c1 = cost[i3 - 1][j2].item();
        const c2 = cost[i3][j2 - 1].item();
        let c, t;
        if (c0 < c1 && c0 < c2) {
          c = c0;
          t = 0;
        } else if (c1 < c0 && c1 < c2) {
          c = c1;
          t = 1;
        } else {
          c = c2;
          t = 2;
        }
        cost[i3].data[j2] = matrix[i3 - 1][j2 - 1].item() + c;
        trace[i3].data[j2] = t;
      }
    }
    let i2 = output_length;
    let j = input_length;
    trace.data.fill(2, 0, outputShape[1]);
    for (let i3 = 0; i3 < outputShape[0]; ++i3) {
      trace[i3].data[0] = 1;
    }
    let text_indices = [];
    let time_indices = [];
    while (i2 > 0 || j > 0) {
      text_indices.push(i2 - 1);
      time_indices.push(j - 1);
      const t = trace[i2][j].item();
      switch (t) {
        case 0:
          --i2;
          --j;
          break;
        case 1:
          --i2;
          break;
        case 2:
          --j;
          break;
        default:
          throw new Error(
            `Internal error in dynamic time warping. Unexpected trace[${i2}, ${j}]. Please file a bug report.`
          );
      }
    }
    text_indices.reverse();
    time_indices.reverse();
    return [text_indices, time_indices];
  }
  function dimsToStride(dims) {
    const stride = new Array(dims.length);
    for (let i2 = dims.length - 1, s2 = 1; i2 >= 0; --i2) {
      stride[i2] = s2;
      s2 *= dims[i2];
    }
    return stride;
  }
  function ones(size) {
    const numElements = size.reduce((a, b) => a * b, 1);
    return new Tensor(
      "int64",
      new BigInt64Array(numElements).fill(/* @__PURE__ */ BigInt("1")),
      size
    );
  }
  function ones_like(tensor) {
    return ones(tensor.dims);
  }
  var TOKEN_TYPES = Object.freeze({
    Text: "Text",
    // The text between Jinja statements or expressions
    NumericLiteral: "NumericLiteral",
    // e.g., 123
    BooleanLiteral: "BooleanLiteral",
    // true or false
    StringLiteral: "StringLiteral",
    // 'string'
    Identifier: "Identifier",
    // Variables, functions, etc.
    Equals: "Equals",
    // =
    OpenParen: "OpenParen",
    // (
    CloseParen: "CloseParen",
    // )
    OpenStatement: "OpenStatement",
    // {%
    CloseStatement: "CloseStatement",
    // %}
    OpenExpression: "OpenExpression",
    // {{
    CloseExpression: "CloseExpression",
    // }}
    OpenSquareBracket: "OpenSquareBracket",
    // [
    CloseSquareBracket: "CloseSquareBracket",
    // ]
    OpenCurlyBracket: "OpenCurlyBracket",
    // {
    CloseCurlyBracket: "CloseCurlyBracket",
    // }
    Comma: "Comma",
    // ,
    Dot: "Dot",
    // .
    Colon: "Colon",
    // :
    Pipe: "Pipe",
    // |
    CallOperator: "CallOperator",
    // ()
    AdditiveBinaryOperator: "AdditiveBinaryOperator",
    // + -
    MultiplicativeBinaryOperator: "MultiplicativeBinaryOperator",
    // * / %
    ComparisonBinaryOperator: "ComparisonBinaryOperator",
    // < > <= >= == !=
    UnaryOperator: "UnaryOperator",
    // ! - +
    // Keywords
    Set: "Set",
    If: "If",
    For: "For",
    In: "In",
    Is: "Is",
    NotIn: "NotIn",
    Else: "Else",
    EndIf: "EndIf",
    ElseIf: "ElseIf",
    EndFor: "EndFor",
    And: "And",
    Or: "Or",
    Not: "UnaryOperator"
  });
  Object.freeze({
    set: TOKEN_TYPES.Set,
    for: TOKEN_TYPES.For,
    in: TOKEN_TYPES.In,
    is: TOKEN_TYPES.Is,
    if: TOKEN_TYPES.If,
    else: TOKEN_TYPES.Else,
    endif: TOKEN_TYPES.EndIf,
    elif: TOKEN_TYPES.ElseIf,
    endfor: TOKEN_TYPES.EndFor,
    and: TOKEN_TYPES.And,
    or: TOKEN_TYPES.Or,
    not: TOKEN_TYPES.Not,
    "not in": TOKEN_TYPES.NotIn,
    // Literals
    true: TOKEN_TYPES.BooleanLiteral,
    false: TOKEN_TYPES.BooleanLiteral
  });
  [
    // Control sequences
    ["{%", TOKEN_TYPES.OpenStatement],
    ["%}", TOKEN_TYPES.CloseStatement],
    ["{{", TOKEN_TYPES.OpenExpression],
    ["}}", TOKEN_TYPES.CloseExpression],
    // Single character tokens
    ["(", TOKEN_TYPES.OpenParen],
    [")", TOKEN_TYPES.CloseParen],
    ["{", TOKEN_TYPES.OpenCurlyBracket],
    ["}", TOKEN_TYPES.CloseCurlyBracket],
    ["[", TOKEN_TYPES.OpenSquareBracket],
    ["]", TOKEN_TYPES.CloseSquareBracket],
    [",", TOKEN_TYPES.Comma],
    [".", TOKEN_TYPES.Dot],
    [":", TOKEN_TYPES.Colon],
    ["|", TOKEN_TYPES.Pipe],
    // Comparison operators
    ["<=", TOKEN_TYPES.ComparisonBinaryOperator],
    [">=", TOKEN_TYPES.ComparisonBinaryOperator],
    ["==", TOKEN_TYPES.ComparisonBinaryOperator],
    ["!=", TOKEN_TYPES.ComparisonBinaryOperator],
    ["<", TOKEN_TYPES.ComparisonBinaryOperator],
    [">", TOKEN_TYPES.ComparisonBinaryOperator],
    // Arithmetic operators
    ["+", TOKEN_TYPES.AdditiveBinaryOperator],
    ["-", TOKEN_TYPES.AdditiveBinaryOperator],
    ["*", TOKEN_TYPES.MultiplicativeBinaryOperator],
    ["/", TOKEN_TYPES.MultiplicativeBinaryOperator],
    ["%", TOKEN_TYPES.MultiplicativeBinaryOperator],
    // Assignment operator
    ["=", TOKEN_TYPES.Equals]
  ];
  const BYTES_TO_UNICODE = (() => {
    const bs = [
      ...Array.from({ length: "~".charCodeAt(0) - "!".charCodeAt(0) + 1 }, (_, i2) => i2 + "!".charCodeAt(0)),
      ...Array.from({ length: "¬".charCodeAt(0) - "¡".charCodeAt(0) + 1 }, (_, i2) => i2 + "¡".charCodeAt(0)),
      ...Array.from({ length: "ÿ".charCodeAt(0) - "®".charCodeAt(0) + 1 }, (_, i2) => i2 + "®".charCodeAt(0))
    ];
    const cs2 = bs.slice();
    let n = 0;
    for (let b = 0; b < 256; ++b) {
      if (!bs.includes(b)) {
        bs.push(b);
        cs2.push(256 + n);
        n += 1;
      }
    }
    const ccs = cs2.map((n2) => String.fromCharCode(n2));
    return Object.fromEntries(bs.map((b, i2) => [b, ccs[i2]]));
  })();
  reverseDictionary(BYTES_TO_UNICODE);
  const WHISPER_LANGUAGES = [
    ["en", "english"],
    ["zh", "chinese"],
    ["de", "german"],
    ["es", "spanish"],
    ["ru", "russian"],
    ["ko", "korean"],
    ["fr", "french"],
    ["ja", "japanese"],
    ["pt", "portuguese"],
    ["tr", "turkish"],
    ["pl", "polish"],
    ["ca", "catalan"],
    ["nl", "dutch"],
    ["ar", "arabic"],
    ["sv", "swedish"],
    ["it", "italian"],
    ["id", "indonesian"],
    ["hi", "hindi"],
    ["fi", "finnish"],
    ["vi", "vietnamese"],
    ["he", "hebrew"],
    ["uk", "ukrainian"],
    ["el", "greek"],
    ["ms", "malay"],
    ["cs", "czech"],
    ["ro", "romanian"],
    ["da", "danish"],
    ["hu", "hungarian"],
    ["ta", "tamil"],
    ["no", "norwegian"],
    ["th", "thai"],
    ["ur", "urdu"],
    ["hr", "croatian"],
    ["bg", "bulgarian"],
    ["lt", "lithuanian"],
    ["la", "latin"],
    ["mi", "maori"],
    ["ml", "malayalam"],
    ["cy", "welsh"],
    ["sk", "slovak"],
    ["te", "telugu"],
    ["fa", "persian"],
    ["lv", "latvian"],
    ["bn", "bengali"],
    ["sr", "serbian"],
    ["az", "azerbaijani"],
    ["sl", "slovenian"],
    ["kn", "kannada"],
    ["et", "estonian"],
    ["mk", "macedonian"],
    ["br", "breton"],
    ["eu", "basque"],
    ["is", "icelandic"],
    ["hy", "armenian"],
    ["ne", "nepali"],
    ["mn", "mongolian"],
    ["bs", "bosnian"],
    ["kk", "kazakh"],
    ["sq", "albanian"],
    ["sw", "swahili"],
    ["gl", "galician"],
    ["mr", "marathi"],
    ["pa", "punjabi"],
    ["si", "sinhala"],
    ["km", "khmer"],
    ["sn", "shona"],
    ["yo", "yoruba"],
    ["so", "somali"],
    ["af", "afrikaans"],
    ["oc", "occitan"],
    ["ka", "georgian"],
    ["be", "belarusian"],
    ["tg", "tajik"],
    ["sd", "sindhi"],
    ["gu", "gujarati"],
    ["am", "amharic"],
    ["yi", "yiddish"],
    ["lo", "lao"],
    ["uz", "uzbek"],
    ["fo", "faroese"],
    ["ht", "haitian creole"],
    ["ps", "pashto"],
    ["tk", "turkmen"],
    ["nn", "nynorsk"],
    ["mt", "maltese"],
    ["sa", "sanskrit"],
    ["lb", "luxembourgish"],
    ["my", "myanmar"],
    ["bo", "tibetan"],
    ["tl", "tagalog"],
    ["mg", "malagasy"],
    ["as", "assamese"],
    ["tt", "tatar"],
    ["haw", "hawaiian"],
    ["ln", "lingala"],
    ["ha", "hausa"],
    ["ba", "bashkir"],
    ["jw", "javanese"],
    ["su", "sundanese"]
  ];
  new Map(WHISPER_LANGUAGES);
  new Map([
    ...WHISPER_LANGUAGES.map(([k, v]) => [v, k]),
    ...[
      ["burmese", "my"],
      ["valencian", "ca"],
      ["flemish", "nl"],
      ["haitian", "ht"],
      ["letzeburgesch", "lb"],
      ["pushto", "ps"],
      ["panjabi", "pa"],
      ["moldavian", "ro"],
      ["moldovan", "ro"],
      ["sinhalese", "si"],
      ["castilian", "es"]
    ]
  ]);
  function loadConfig(pretrained_model_name_or_path, options) {
    return __async(this, null, function* () {
      let info = yield getModelJSON(pretrained_model_name_or_path, "config.json", true, options);
      return info;
    });
  }
  class PretrainedConfig {
    // NOTE: Typo in original
    /**
     * Create a new PreTrainedTokenizer instance.
     * @param {Object} configJSON The JSON of the config.
     */
    constructor(configJSON) {
      this.model_type = null;
      this.is_encoder_decoder = false;
      Object.assign(this, configJSON);
    }
    /**
     * Loads a pre-trained config from the given `pretrained_model_name_or_path`. 
     * 
     * @param {string} pretrained_model_name_or_path The path to the pre-trained config.
     * @param {PretrainedOptions} options Additional options for loading the config.
     * @throws {Error} Throws an error if the config.json is not found in the `pretrained_model_name_or_path`.
     * 
     * @returns {Promise<PretrainedConfig>} A new instance of the `PretrainedConfig` class.
     */
    static from_pretrained(_0) {
      return __async(this, arguments, function* (pretrained_model_name_or_path, {
        progress_callback = null,
        config: config2 = null,
        cache_dir = null,
        local_files_only = false,
        revision = "main"
      } = {}) {
        let data = config2 != null ? config2 : yield loadConfig(pretrained_model_name_or_path, {
          progress_callback,
          cache_dir,
          local_files_only,
          revision
        });
        return new this(data);
      });
    }
  }
  class AutoConfig {
    /** @type {PretrainedConfig.from_pretrained} */
    static from_pretrained(...args) {
      return __async(this, null, function* () {
        return PretrainedConfig.from_pretrained(...args);
      });
    }
  }
  class LogitsProcessorList extends Callable {
    /**
     * Constructs a new instance of `LogitsProcessorList`.
     */
    constructor() {
      super();
      this.processors = [];
    }
    /**
     * Adds a new logits processor to the list.
     *
     * @param {LogitsProcessor} item The logits processor function to add.
     */
    push(item) {
      this.processors.push(item);
    }
    /**
     * Adds multiple logits processors to the list.
     *
     * @param {LogitsProcessor[]} items The logits processor functions to add.
     */
    extend(items2) {
      this.processors.push(...items2);
    }
    /**
     * Applies all logits processors in the list to a batch of logits, modifying them in-place.
     *
     * @param {number[]} input_ids The input IDs for the language model.
     * @param {number[][]} batchedLogits A 2D array of logits, where each row corresponds to a single
     *                                                input sequence in the batch.
     */
    _call(input_ids, batchedLogits) {
      for (let logits of batchedLogits) {
        this.processors.forEach(
          (func) => func(input_ids, logits)
        );
      }
    }
    [Symbol.iterator]() {
      return this.processors.values();
    }
  }
  class LogitsProcessor extends Callable {
    /**
     * Apply the processor to the input logits.
     *
     * @abstract
     * @param {Array} input_ids The input ids.
     * @param {Tensor} logits The logits to process.
     * @throws {Error} Throws an error if `_call` is not implemented in the subclass.
     */
    _call(input_ids, logits) {
      throw Error("`_call` should be implemented in a subclass");
    }
  }
  class ForceTokensLogitsProcessor extends LogitsProcessor {
    /**
     * Constructs a new instance of `ForceTokensLogitsProcessor`.
     * 
     * @param {Array} forced_decoder_ids The ids of tokens that should be forced.
     */
    constructor(forced_decoder_ids) {
      super();
      this.force_token_map = Object.fromEntries(forced_decoder_ids != null ? forced_decoder_ids : []);
    }
    /**
     * Apply the processor to the input logits.
     *
     * @param {Array} input_ids The input ids.
     * @param {Tensor} logits The logits to process.
     * @returns {Tensor} The processed logits.
     */
    _call(input_ids, logits) {
      let map2 = this.force_token_map[input_ids.length];
      if (exists(map2)) {
        logits.data.fill(-Infinity);
        logits.data[map2] = 0;
      }
      return logits;
    }
  }
  class ForcedBOSTokenLogitsProcessor extends LogitsProcessor {
    /**
     * Create a ForcedBOSTokenLogitsProcessor.
     * @param {number} bos_token_id The ID of the beginning-of-sequence token to be forced.
     */
    constructor(bos_token_id) {
      super();
      this.bos_token_id = bos_token_id;
    }
    /**
     * Apply the BOS token forcing to the logits.
     * @param {Array} input_ids The input IDs.
     * @param {Object} logits The logits.
     * @returns {Object} The logits with BOS token forcing.
     */
    _call(input_ids, logits) {
      if (input_ids.length === 1) {
        logits.data.fill(-Infinity);
        logits.data[this.bos_token_id] = 0;
      }
      return logits;
    }
  }
  class ForcedEOSTokenLogitsProcessor extends LogitsProcessor {
    /**
     * Create a ForcedEOSTokenLogitsProcessor.
     * @param {number} max_length Max length of the sequence.
     * @param {number|number[]} forced_eos_token_id The ID of the end-of-sequence token to be forced.
     */
    constructor(max_length, forced_eos_token_id) {
      super();
      this.max_length = max_length;
      this.forced_eos_token_id = forced_eos_token_id;
    }
    /**
     * Apply the processor to input_ids and logits.
     * 
     * @param {number[]} input_ids The input ids.
     * @param {Tensor} logits The logits tensor.
     */
    _call(input_ids, logits) {
    }
  }
  class SuppressTokensAtBeginLogitsProcessor extends LogitsProcessor {
    /**
     * Create a SuppressTokensAtBeginLogitsProcessor.
     * @param {number[]} begin_suppress_tokens The IDs of the tokens to suppress.
     * @param {number} begin_index The number of tokens to generate before suppressing tokens.
     */
    constructor(begin_suppress_tokens, begin_index) {
      super();
      this.begin_suppress_tokens = begin_suppress_tokens;
      this.begin_index = begin_index;
    }
    /**
     * Apply the BOS token forcing to the logits.
     * @param {Array} input_ids The input IDs.
     * @param {Object} logits The logits.
     * @returns {Object} The logits with BOS token forcing.
     */
    _call(input_ids, logits) {
      if (input_ids.length === this.begin_index) {
        for (let token_id of this.begin_suppress_tokens) {
          logits.data[token_id] = -Infinity;
        }
      }
      return logits;
    }
  }
  class WhisperTimeStampLogitsProcessor extends LogitsProcessor {
    /**
     * Constructs a new WhisperTimeStampLogitsProcessor.
     * @param {Object} generate_config The config object passed to the `generate()` method of a transformer model.
     * @param {number} generate_config.eos_token_id The ID of the end-of-sequence token.
     * @param {number} generate_config.no_timestamps_token_id The ID of the token used to indicate that a token should not have a timestamp.
     * @param {number[][]} [generate_config.forced_decoder_ids] An array of two-element arrays representing decoder IDs that are forced to appear in the output. The second element of each array indicates whether the token is a timestamp.
     * @param {number} [generate_config.max_initial_timestamp_index] The maximum index at which an initial timestamp can appear.
     */
    constructor(generate_config) {
      super();
      this.eos_token_id = generate_config.eos_token_id;
      this.no_timestamps_token_id = generate_config.no_timestamps_token_id;
      this.timestamp_begin = this.no_timestamps_token_id + 1;
      this.begin_index = (generate_config.forced_decoder_ids || []).length + 2;
      if (generate_config.forced_decoder_ids.slice(-1)[0][1] === this.no_timestamps_token_id) {
        this.begin_index -= 1;
      }
      this.max_initial_timestamp_index = generate_config.max_initial_timestamp_index;
    }
    /**
     * Modify the logits to handle timestamp tokens.
     * @param {Array} input_ids The input sequence of tokens.
     * @param {Tensor} logits The logits output by the model.
     * @returns {Tensor} The modified logits.
     */
    _call(input_ids, logits) {
      const logitsData = (
        /** @type {Float32Array} */
        logits.data
      );
      logitsData[this.no_timestamps_token_id] = -Infinity;
      if (input_ids.length === this.begin_index - 1) {
        logitsData.fill(-Infinity);
        logitsData[this.timestamp_begin] = 0;
        return logits;
      }
      const seq = input_ids.slice(this.begin_index);
      const last_was_timestamp = seq.length >= 1 && seq[seq.length - 1] >= this.timestamp_begin;
      const penultimate_was_timestamp = seq.length < 2 || seq[seq.length - 2] >= this.timestamp_begin;
      if (last_was_timestamp) {
        if (penultimate_was_timestamp) {
          logitsData.subarray(this.timestamp_begin).fill(-Infinity);
        } else {
          logitsData.subarray(0, this.eos_token_id).fill(-Infinity);
        }
      }
      if (input_ids.length === this.begin_index && this.max_initial_timestamp_index !== null) {
        const last_allowed = this.timestamp_begin + this.max_initial_timestamp_index;
        logitsData.subarray(last_allowed + 1).fill(-Infinity);
      }
      const logprobs = log_softmax(logitsData);
      const timestamp_logprob = Math.log(logprobs.subarray(this.timestamp_begin).map(Math.exp).reduce((a, b) => a + b));
      const max_text_token_logprob = max(logprobs.subarray(0, this.timestamp_begin))[0];
      if (timestamp_logprob > max_text_token_logprob) {
        logitsData.subarray(0, this.timestamp_begin).fill(-Infinity);
      }
      return logits;
    }
  }
  class NoRepeatNGramLogitsProcessor extends LogitsProcessor {
    /**
     * Create a NoRepeatNGramLogitsProcessor.
     * @param {number} no_repeat_ngram_size The no-repeat-ngram size. All ngrams of this size can only occur once.
     */
    constructor(no_repeat_ngram_size) {
      super();
      this.no_repeat_ngram_size = no_repeat_ngram_size;
    }
    /**
     * Generate n-grams from a sequence of token ids.
     * @param {number[]} prevInputIds List of previous input ids
     * @returns {Map<string, number[]>} Map of generated n-grams
     */
    getNgrams(prevInputIds) {
      var _a3;
      const curLen = prevInputIds.length;
      const ngrams = [];
      for (let j = 0; j < curLen + 1 - this.no_repeat_ngram_size; ++j) {
        const ngram = [];
        for (let k = 0; k < this.no_repeat_ngram_size; ++k) {
          ngram.push(prevInputIds[j + k]);
        }
        ngrams.push(ngram);
      }
      const generatedNgram = /* @__PURE__ */ new Map();
      for (const ngram of ngrams) {
        const prevNgram = ngram.slice(0, ngram.length - 1);
        const prevNgramKey = JSON.stringify(prevNgram);
        const prevNgramValue = (_a3 = generatedNgram.get(prevNgramKey)) != null ? _a3 : [];
        prevNgramValue.push(ngram[ngram.length - 1]);
        generatedNgram.set(prevNgramKey, prevNgramValue);
      }
      return generatedNgram;
    }
    /**
     * Generate n-grams from a sequence of token ids.
     * @param {Map<string, number[]>} bannedNgrams Map of banned n-grams
     * @param {number[]} prevInputIds List of previous input ids
     * @returns {number[]} Map of generated n-grams
     */
    getGeneratedNgrams(bannedNgrams, prevInputIds) {
      var _a3;
      const ngramIdx = prevInputIds.slice(prevInputIds.length + 1 - this.no_repeat_ngram_size, prevInputIds.length);
      const banned = (_a3 = bannedNgrams.get(JSON.stringify(ngramIdx))) != null ? _a3 : [];
      return banned;
    }
    /**
     * Calculate banned n-gram tokens
     * @param {number[]} prevInputIds List of previous input ids
     * @returns {number[]} Map of generated n-grams
     */
    calcBannedNgramTokens(prevInputIds) {
      const bannedTokens = [];
      if (prevInputIds.length + 1 < this.no_repeat_ngram_size) {
        return bannedTokens;
      } else {
        const generatedNgrams = this.getNgrams(prevInputIds);
        const bannedTokens2 = this.getGeneratedNgrams(generatedNgrams, prevInputIds);
        return bannedTokens2;
      }
    }
    /**
     * Apply the no-repeat-ngram processor to the logits.
     * @param {Array} input_ids The input IDs.
     * @param {Object} logits The logits.
     * @returns {Object} The logits with no-repeat-ngram processing.
     */
    _call(input_ids, logits) {
      const bannedTokens = this.calcBannedNgramTokens(input_ids);
      for (const token of bannedTokens) {
        logits.data[token] = -Infinity;
      }
      return logits;
    }
  }
  class RepetitionPenaltyLogitsProcessor extends LogitsProcessor {
    /**
     * Create a RepetitionPenaltyLogitsProcessor.
     * @param {number} penalty The penalty to apply for repeated tokens.
     */
    constructor(penalty) {
      super();
      this.penalty = penalty;
    }
    /**
     * Apply the repetition penalty to the logits.
     * @param {Array} input_ids The input IDs.
     * @param {Object} logits The logits.
     * @returns {Object} The logits with repetition penalty processing.
     */
    _call(input_ids, logits) {
      for (const input_id of input_ids) {
        if (logits.data[input_id] < 0) {
          logits.data[input_id] *= this.penalty;
        } else {
          logits.data[input_id] /= this.penalty;
        }
      }
      return logits;
    }
  }
  class MinLengthLogitsProcessor extends LogitsProcessor {
    /**
     * Create a MinLengthLogitsProcessor.
     * @param {number} min_length The minimum length below which the score of `eos_token_id` is set to negative infinity.
     * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token.
     */
    constructor(min_length, eos_token_id) {
      super();
      this.min_length = min_length;
      this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id];
    }
    /**
     * Apply logit processor.
     * @param {Array} input_ids The input IDs.
     * @param {Object} logits The logits.
     * @returns {Object} The processed logits.
     */
    _call(input_ids, logits) {
      if (input_ids.length < this.min_length) {
        for (const eos_token of this.eos_token_id) {
          logits.data[eos_token] = -Infinity;
        }
      }
      return logits;
    }
  }
  class MinNewTokensLengthLogitsProcessor extends LogitsProcessor {
    /**
     * Create a MinNewTokensLengthLogitsProcessor.
     * @param {number} prompt_length_to_skip The input tokens length.
     * @param {number} min_new_tokens The minimum *new* tokens length below which the score of `eos_token_id` is set to negative infinity.
     * @param {number|number[]} eos_token_id The ID/IDs of the end-of-sequence token.
     */
    constructor(prompt_length_to_skip, min_new_tokens, eos_token_id) {
      super();
      this.prompt_length_to_skip = prompt_length_to_skip;
      this.min_new_tokens = min_new_tokens;
      this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id];
    }
    /**
     * Apply logit processor.
     * @param {Array} input_ids The input IDs.
     * @param {Object} logits The logits.
     * @returns {Object} The processed logits.
     */
    _call(input_ids, logits) {
      const new_tokens_length = input_ids.length - this.prompt_length_to_skip;
      if (new_tokens_length < this.min_new_tokens) {
        for (const eos_token of this.eos_token_id) {
          logits.data[eos_token] = -Infinity;
        }
      }
      return logits;
    }
  }
  class NoBadWordsLogitsProcessor extends LogitsProcessor {
    /**
     * Create a `NoBadWordsLogitsProcessor`.
     * @param {number[][]} bad_words_ids List of list of token ids that are not allowed to be generated.
     * @param {number|number[]} eos_token_id The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
     */
    constructor(bad_words_ids, eos_token_id) {
      super();
      this.bad_words_ids = bad_words_ids;
      this.eos_token_id = Array.isArray(eos_token_id) ? eos_token_id : [eos_token_id];
    }
    /**
     * Apply logit processor.
     * @param {Array} input_ids The input IDs.
     * @param {Object} logits The logits.
     * @returns {Object} The processed logits.
     */
    _call(input_ids, logits) {
      for (const bad_word_ids of this.bad_words_ids) {
        let mark = true;
        for (let i2 = 1; i2 <= bad_word_ids.length - 1 && bad_word_ids.length < input_ids.length; ++i2) {
          if (bad_word_ids.at(-i2 - 1) !== input_ids.at(-i2)) {
            mark = false;
            break;
          }
        }
        if (mark) {
          logits.data[bad_word_ids.at(-1)] = -Infinity;
        }
      }
      return logits;
    }
  }
  const GenerationConfig = (
    /** @type {any} */
    class {
      /**
       * Create a new GenerationConfig object.
       * @param {GenerationConfigType} kwargs 
       */
      constructor(kwargs = {}) {
        var _a3, _b2, _c2, _d2, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H, _I, _J, _K, _L, _M, _N, _O, _P, _Q, _R;
        this.max_length = (_a3 = kwargs.max_length) != null ? _a3 : 20;
        this.max_new_tokens = (_b2 = kwargs.max_new_tokens) != null ? _b2 : null;
        this.min_length = (_c2 = kwargs.min_length) != null ? _c2 : 0;
        this.min_new_tokens = (_d2 = kwargs.min_new_tokens) != null ? _d2 : null;
        this.early_stopping = (_e = kwargs.early_stopping) != null ? _e : false;
        this.max_time = (_f = kwargs.max_time) != null ? _f : null;
        this.do_sample = (_g = kwargs.do_sample) != null ? _g : false;
        this.num_beams = (_h = kwargs.num_beams) != null ? _h : 1;
        this.num_beam_groups = (_i = kwargs.num_beam_groups) != null ? _i : 1;
        this.penalty_alpha = (_j = kwargs.penalty_alpha) != null ? _j : null;
        this.use_cache = (_k = kwargs.use_cache) != null ? _k : true;
        this.temperature = (_l = kwargs.temperature) != null ? _l : 1;
        this.top_k = (_m = kwargs.top_k) != null ? _m : 50;
        this.top_p = (_n = kwargs.top_p) != null ? _n : 1;
        this.typical_p = (_o = kwargs.typical_p) != null ? _o : 1;
        this.epsilon_cutoff = (_p = kwargs.epsilon_cutoff) != null ? _p : 0;
        this.eta_cutoff = (_q = kwargs.eta_cutoff) != null ? _q : 0;
        this.diversity_penalty = (_r = kwargs.diversity_penalty) != null ? _r : 0;
        this.repetition_penalty = (_s = kwargs.repetition_penalty) != null ? _s : 1;
        this.encoder_repetition_penalty = (_t = kwargs.encoder_repetition_penalty) != null ? _t : 1;
        this.length_penalty = (_u = kwargs.length_penalty) != null ? _u : 1;
        this.no_repeat_ngram_size = (_v = kwargs.no_repeat_ngram_size) != null ? _v : 0;
        this.bad_words_ids = (_w = kwargs.bad_words_ids) != null ? _w : null;
        this.force_words_ids = (_x = kwargs.force_words_ids) != null ? _x : null;
        this.renormalize_logits = (_y = kwargs.renormalize_logits) != null ? _y : false;
        this.constraints = (_z = kwargs.constraints) != null ? _z : null;
        this.forced_bos_token_id = (_A = kwargs.forced_bos_token_id) != null ? _A : null;
        this.forced_eos_token_id = (_B = kwargs.forced_eos_token_id) != null ? _B : null;
        this.remove_invalid_values = (_C = kwargs.remove_invalid_values) != null ? _C : false;
        this.exponential_decay_length_penalty = (_D = kwargs.exponential_decay_length_penalty) != null ? _D : null;
        this.suppress_tokens = (_E = kwargs.suppress_tokens) != null ? _E : null;
        this.begin_suppress_tokens = (_F = kwargs.begin_suppress_tokens) != null ? _F : null;
        this.forced_decoder_ids = (_G = kwargs.forced_decoder_ids) != null ? _G : null;
        this.num_return_sequences = (_H = kwargs.num_return_sequences) != null ? _H : 1;
        this.output_attentions = (_I = kwargs.output_attentions) != null ? _I : false;
        this.output_hidden_states = (_J = kwargs.output_hidden_states) != null ? _J : false;
        this.output_scores = (_K = kwargs.output_scores) != null ? _K : false;
        this.return_dict_in_generate = (_L = kwargs.return_dict_in_generate) != null ? _L : false;
        this.pad_token_id = (_M = kwargs.pad_token_id) != null ? _M : null;
        this.bos_token_id = (_N = kwargs.bos_token_id) != null ? _N : null;
        this.eos_token_id = (_O = kwargs.eos_token_id) != null ? _O : null;
        this.encoder_no_repeat_ngram_size = (_P = kwargs.encoder_no_repeat_ngram_size) != null ? _P : 0;
        this.decoder_start_token_id = (_Q = kwargs.decoder_start_token_id) != null ? _Q : null;
        this.generation_kwargs = (_R = kwargs.generation_kwargs) != null ? _R : {};
      }
    }
  );
  class Sampler extends Callable {
    /**
     * Creates a new Sampler object with the specified generation config.
     * @param {GenerationConfigType} generation_config The generation config.
     */
    constructor(generation_config) {
      super();
      this.generation_config = generation_config;
    }
    /**
     * Executes the sampler, using the specified logits.
     * @param {Tensor} logits
     * @param {number} index
     * @returns {void}
     */
    _call(logits, index2 = -1) {
      return this.sample(logits, index2);
    }
    /**
     * Abstract method for sampling the logits.
     * @param {Tensor} logits
     * @param {number} index
     * @throws {Error}
     */
    sample(logits, index2) {
      throw Error("sample should be implemented in subclasses.");
    }
    /**
     * Returns the specified logits as an array, with temperature applied.
     * @param {Tensor} logits
     * @param {number} index
     * @returns {Float32Array}
     */
    getLogits(logits, index2) {
      let vocabSize = logits.dims.at(-1);
      let logs = (
        /** @type {Float32Array} */
        logits.data
      );
      if (index2 === -1) {
        logs = logs.slice(-vocabSize);
      } else {
        let startIndex = index2 * vocabSize;
        logs = logs.slice(startIndex, startIndex + vocabSize);
      }
      if (this.generation_config.temperature > 0) {
        logs = logs.map((x) => x / this.generation_config.temperature);
      }
      return logs;
    }
    /**
     * Selects an item randomly based on the specified probabilities.
     * @param {Array} probabilities An array of probabilities to use for selection.
     * @returns {number} The index of the selected item.
     */
    randomSelect(probabilities) {
      let sumProbabilities = probabilities.reduce((acc, curr) => acc + curr, 0);
      let r = Math.random() * sumProbabilities;
      for (let i2 = 0; i2 < probabilities.length; ++i2) {
        r -= probabilities[i2];
        if (r <= 0) {
          return i2;
        }
      }
      return 0;
    }
    /**
     * Returns a Sampler object based on the specified options.
     * @param {GenerationConfigType} generation_config An object containing options for the sampler.
     * @returns {Sampler} A Sampler object.
     */
    static getSampler(generation_config) {
      if (generation_config.do_sample) {
        return new MultinomialSampler(generation_config);
      } else if (generation_config.num_beams > 1) {
        return new BeamSearchSampler(generation_config);
      } else {
        if (generation_config.num_return_sequences > 1) {
          throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${generation_config.num_return_sequences}.`);
        }
        return new GreedySampler(generation_config);
      }
    }
  }
  class GreedySampler extends Sampler {
    /**
     * Sample the maximum probability of a given logits tensor.
     * @param {Tensor} logits
     * @param {number} [index=-1]
     * @returns {Array} An array with a single tuple, containing the index of the maximum value and a meaningless score (since this is a greedy search).
     */
    sample(logits, index2 = -1) {
      let logs = this.getLogits(logits, index2);
      let argmax = max(logs)[1];
      return [
        [argmax, 0]
      ];
    }
  }
  class MultinomialSampler extends Sampler {
    /**
     * Sample from the logits.
     * @param {Tensor} logits
     * @param {number} index
     * @returns {Array}
     */
    sample(logits, index2 = -1) {
      let k = logits.dims.at(-1);
      if (this.generation_config.top_k > 0) {
        k = Math.min(this.generation_config.top_k, k);
      }
      const logs = this.getLogits(logits, index2);
      const topLogits = getTopItems(logs, k);
      const probabilities = softmax(topLogits.map((x) => x[1]));
      return Array.from({ length: this.generation_config.num_beams }, () => {
        const sampledIndex = this.randomSelect(probabilities);
        return [
          topLogits[sampledIndex][0],
          // token id
          Math.log(probabilities[sampledIndex])
          // score
        ];
      });
    }
  }
  class BeamSearchSampler extends Sampler {
    /**
     * Sample from the logits.
     * @param {Tensor} logits
     * @param {number} index
     * @returns {Array}
     */
    sample(logits, index2 = -1) {
      let k = logits.dims.at(-1);
      if (this.generation_config.top_k > 0) {
        k = Math.min(this.generation_config.top_k, k);
      }
      const logs = this.getLogits(logits, index2);
      const topLogits = getTopItems(logs, k);
      const probabilities = softmax(topLogits.map((x) => x[1]));
      return Array.from({ length: this.generation_config.num_beams }, (_, i2) => {
        return [
          topLogits[i2][0],
          // token id
          Math.log(probabilities[i2])
          // score
        ];
      });
    }
  }
  const { InferenceSession, Tensor: ONNXTensor, env } = ONNX;
  const MODEL_TYPES = {
    EncoderOnly: 0,
    EncoderDecoder: 1,
    Seq2Seq: 2,
    Vision2Seq: 3,
    DecoderOnly: 4,
    MaskGeneration: 5
  };
  const MODEL_TYPE_MAPPING = /* @__PURE__ */ new Map();
  const MODEL_NAME_TO_CLASS_MAPPING = /* @__PURE__ */ new Map();
  const MODEL_CLASS_TO_NAME_MAPPING = /* @__PURE__ */ new Map();
  function constructSession(pretrained_model_name_or_path, fileName, options) {
    return __async(this, null, function* () {
      let modelFileName = `onnx/${fileName}${options.quantized ? "_quantized" : ""}.onnx`;
      let buffer2 = yield getModelFile(pretrained_model_name_or_path, modelFileName, true, options);
      try {
        return yield InferenceSession.create(buffer2, {
          executionProviders
        });
      } catch (err) {
        if (executionProviders.length === 1 && executionProviders[0] === "wasm") {
          throw err;
        }
        console.warn(err);
        console.warn(
          "Something went wrong during model construction (most likely a missing operation). Using `wasm` as a fallback. "
        );
        return yield InferenceSession.create(buffer2, {
          executionProviders: ["wasm"]
        });
      }
    });
  }
  function validateInputs(session, inputs) {
    const checkedInputs = /* @__PURE__ */ Object.create(null);
    const missingInputs = [];
    for (const inputName of session.inputNames) {
      const tensor = inputs[inputName];
      if (!(tensor instanceof Tensor)) {
        missingInputs.push(inputName);
        continue;
      }
      checkedInputs[inputName] = env.wasm.proxy ? tensor.clone() : tensor;
    }
    if (missingInputs.length > 0) {
      throw new Error(
        `An error occurred during model execution: "Missing the following inputs: ${missingInputs.join(", ")}.`
      );
    }
    const numInputsProvided = Object.keys(inputs).length;
    const numInputsNeeded = session.inputNames.length;
    if (numInputsProvided > numInputsNeeded) {
      let ignored = Object.keys(inputs).filter((inputName) => !session.inputNames.includes(inputName));
      console.warn(`WARNING: Too many inputs were provided (${numInputsProvided} > ${numInputsNeeded}). The following inputs will be ignored: "${ignored.join(", ")}".`);
    }
    return checkedInputs;
  }
  function sessionRun(session, inputs) {
    return __async(this, null, function* () {
      const checkedInputs = validateInputs(session, inputs);
      try {
        let output = yield session.run(checkedInputs);
        output = replaceTensors(output);
        return output;
      } catch (e) {
        console.error(`An error occurred during model execution: "${e}".`);
        console.error("Inputs given to model:", checkedInputs);
        throw e;
      }
    });
  }
  function replaceTensors(obj) {
    for (let prop in obj) {
      if (obj[prop] instanceof ONNXTensor) {
        obj[prop] = new Tensor(obj[prop]);
      } else if (typeof obj[prop] === "object") {
        replaceTensors(obj[prop]);
      }
    }
    return obj;
  }
  function toI64Tensor(items2) {
    if (items2 instanceof Tensor) {
      return items2;
    }
    if (items2.length === 0) {
      throw Error("items must be non-empty");
    }
    if (Array.isArray(items2[0])) {
      if (items2.some((x) => x.length !== items2[0].length)) {
        throw Error("Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.");
      }
      return new Tensor(
        "int64",
        BigInt64Array.from(items2.flat().map((x) => BigInt(x))),
        [items2.length, items2[0].length]
      );
    } else {
      return new Tensor(
        "int64",
        BigInt64Array.from(items2.map((x) => BigInt(x))),
        [1, items2.length]
      );
    }
  }
  function prepareAttentionMask(self2, tokens) {
    var _a3, _b2;
    let pad_token_id = (_a3 = self2.config.pad_token_id) != null ? _a3 : null;
    let eos_token_id = (_b2 = self2.config.eos_token_id) != null ? _b2 : null;
    if (isIntegralNumber(eos_token_id)) {
      eos_token_id = [eos_token_id];
    }
    let is_pad_token_in_inputs = tokens.indexOf(pad_token_id) !== -1;
    let is_pad_token_not_equal_to_eos_token_id = eos_token_id === null || !eos_token_id.includes(pad_token_id);
    if (is_pad_token_in_inputs && is_pad_token_not_equal_to_eos_token_id) {
      let data = BigInt64Array.from(
        // Note: != so that int matches bigint
        // @ts-ignore
        tokens.data.map((x) => x != pad_token_id)
      );
      return new Tensor("int64", data, tokens.dims);
    } else {
      return ones_like(tokens);
    }
  }
  function preparePositionIds(session, feeds, use_cache_branch) {
    if (!session.inputNames.includes("position_ids")) return;
    const data = new BigInt64Array(feeds.attention_mask.data.length);
    for (let i2 = 0; i2 < feeds.attention_mask.dims[0]; ++i2) {
      let start = i2 * feeds.attention_mask.dims[1];
      let sum = BigInt(0);
      for (let j = 0; j < feeds.attention_mask.dims[1]; ++j) {
        const index2 = start + j;
        if (feeds.attention_mask.data[index2] === /* @__PURE__ */ BigInt("0")) {
          data[index2] = BigInt(1);
        } else {
          data[index2] = sum;
          sum += feeds.attention_mask.data[index2];
        }
      }
    }
    feeds.position_ids = new Tensor("int64", data, feeds.attention_mask.dims);
    if (use_cache_branch) {
      feeds.position_ids = feeds.position_ids.slice(null, -1).unsqueeze_(-1);
    }
  }
  function boolTensor(value) {
    return new Tensor("bool", [value], [1]);
  }
  function seq2seqForward(self2, model_inputs) {
    return __async(this, null, function* () {
      let { encoder_outputs, past_key_values } = model_inputs;
      if (!encoder_outputs) {
        encoder_outputs = (yield encoderForward(self2, model_inputs)).last_hidden_state;
      }
      let decoderFeeds = {
        input_ids: model_inputs.decoder_input_ids,
        encoder_hidden_states: encoder_outputs
      };
      const use_cache_branch = !!past_key_values;
      if (self2.decoder_merged_session.inputNames.includes("use_cache_branch")) {
        decoderFeeds.use_cache_branch = boolTensor(use_cache_branch);
      }
      if (self2.decoder_merged_session.inputNames.includes("encoder_attention_mask")) {
        decoderFeeds.encoder_attention_mask = model_inputs.attention_mask;
      }
      preparePositionIds(self2.decoder_merged_session, decoderFeeds, use_cache_branch);
      self2.addPastKeyValues(decoderFeeds, past_key_values);
      const decoderResults = yield sessionRun(self2.decoder_merged_session, decoderFeeds);
      let logits = decoderResults.logits;
      past_key_values = self2.getPastKeyValues(decoderResults, past_key_values);
      const attns = self2.getAttentions(decoderResults);
      return new Seq2SeqLMOutput(__spreadValues({ logits, past_key_values, encoder_outputs }, attns));
    });
  }
  function seq2seqStartBeams(self2, inputTokenIds, generation_config, numOutputTokens) {
    var _a3, _b2, _c2, _d2;
    let beams = [];
    let beamId = 0;
    const requires_attention_mask = (_a3 = self2.requires_attention_mask) != null ? _a3 : true;
    let decoder_input_ids = (_d2 = (_c2 = (_b2 = generation_config.decoder_input_ids) != null ? _b2 : generation_config.decoder_start_token_id) != null ? _c2 : generation_config.bos_token_id) != null ? _d2 : generation_config.eos_token_id;
    if (decoder_input_ids instanceof Tensor) {
      decoder_input_ids = decoder_input_ids.tolist().flat();
    } else if (!Array.isArray(decoder_input_ids)) {
      decoder_input_ids = [decoder_input_ids];
    }
    for (let tokens of inputTokenIds) {
      tokens.dims = [1, ...tokens.dims];
      let start = {
        inputs: tokens,
        encoder_outputs: null,
        prev_model_outputs: null,
        output_token_ids: decoder_input_ids,
        done: false,
        score: 0,
        id: beamId++
        // assign unique id to beams
      };
      if (requires_attention_mask) {
        start.attention_mask = prepareAttentionMask(self2, tokens);
      }
      beams.push(start);
    }
    return beams;
  }
  function seq2seqRunBeam(self2, beam) {
    return __async(this, null, function* () {
      var _a3;
      const input_name = self2.main_input_name;
      let decoder_input_ids = beam.output_token_ids;
      if (beam.prev_model_outputs) {
        decoder_input_ids = decoder_input_ids.slice(-1);
      }
      let model_inputs = {
        [input_name]: beam.inputs,
        decoder_input_ids: toI64Tensor(decoder_input_ids),
        encoder_outputs: beam.encoder_outputs,
        past_key_values: (_a3 = beam.prev_model_outputs) == null ? void 0 : _a3.past_key_values
      };
      if (beam.attention_mask) {
        model_inputs.attention_mask = beam.attention_mask;
      }
      let output = yield self2.forward(model_inputs);
      beam.prev_model_outputs = output;
      beam.encoder_outputs = output.encoder_outputs;
      return output;
    });
  }
  function seq2seqUpdatebeam(beam, newTokenId) {
    beam.output_token_ids = [...beam.output_token_ids, newTokenId];
  }
  function encoderForward(self2, model_inputs) {
    return __async(this, null, function* () {
      const encoderFeeds = /* @__PURE__ */ Object.create(null);
      for (const key of self2.session.inputNames) {
        encoderFeeds[key] = model_inputs[key];
      }
      if (self2.session.inputNames.includes("token_type_ids") && !encoderFeeds.token_type_ids) {
        encoderFeeds.token_type_ids = new Tensor(
          "int64",
          new BigInt64Array(encoderFeeds.input_ids.data.length),
          encoderFeeds.input_ids.dims
        );
      }
      return yield sessionRun(self2.session, encoderFeeds);
    });
  }
  function decoderForward(self2, model_inputs) {
    return __async(this, null, function* () {
      let { input_ids, past_key_values, attention_mask } = model_inputs;
      let decoderFeeds = {
        input_ids,
        attention_mask: attention_mask != null ? attention_mask : prepareAttentionMask(self2, input_ids)
      };
      const use_cache_branch = !!past_key_values;
      if (self2.session.inputNames.includes("use_cache_branch")) {
        decoderFeeds.use_cache_branch = boolTensor(use_cache_branch);
      }
      preparePositionIds(self2.session, decoderFeeds, use_cache_branch);
      self2.addPastKeyValues(decoderFeeds, past_key_values);
      let decoderResults = yield sessionRun(self2.session, decoderFeeds);
      let logits = decoderResults.logits;
      past_key_values = self2.getPastKeyValues(decoderResults, past_key_values);
      return { logits, past_key_values };
    });
  }
  function decoderStartBeams(self2, inputTokenIds, generation_config, numOutputTokens, inputs_attention_mask) {
    let beams = [];
    let beamId = 0;
    for (let tokens of inputTokenIds) {
      let output_token_ids = tokens.tolist().map(Number);
      tokens.dims = [1, ...tokens.dims];
      let attn_mask;
      if (inputs_attention_mask) {
        attn_mask = inputs_attention_mask[beamId];
        attn_mask.dims = [1, ...attn_mask.dims];
      } else {
        attn_mask = prepareAttentionMask(self2, tokens);
      }
      let start = {
        input: tokens,
        model_input_ids: tokens,
        attention_mask: attn_mask,
        prev_model_outputs: null,
        output_token_ids,
        num_output_tokens: numOutputTokens,
        done: false,
        score: 0,
        id: beamId++
        // assign unique id to beams
      };
      beams.push(start);
    }
    return beams;
  }
  function decoderRunBeam(self2, beam) {
    return __async(this, null, function* () {
      var _a3;
      let attnMaskData = new BigInt64Array(beam.output_token_ids.length).fill(/* @__PURE__ */ BigInt("1"));
      let model_inputs = {
        input_ids: beam.model_input_ids,
        attention_mask: new Tensor(
          "int64",
          attnMaskData,
          [1, attnMaskData.length]
        ),
        past_key_values: (_a3 = beam.prev_model_outputs) == null ? void 0 : _a3.past_key_values
      };
      let output = yield self2.forward(model_inputs);
      beam.prev_model_outputs = output;
      return output;
    });
  }
  function decoderUpdatebeam(beam, newTokenId) {
    beam.output_token_ids = [...beam.output_token_ids, newTokenId];
    beam.model_input_ids = new Tensor("int64", [BigInt(newTokenId)], [1, 1]);
  }
  class PreTrainedModel extends Callable {
    /**
     * Creates a new instance of the `PreTrainedModel` class.
     * @param {Object} config The model configuration.
     * @param {any} session session for the model.
     */
    constructor(config2, session) {
      super();
      __publicField2(this, "main_input_name", "input_ids");
      this.config = config2;
      this.session = session;
      const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this.constructor);
      const modelType = MODEL_TYPE_MAPPING.get(modelName);
      this.can_generate = false;
      this._runBeam = null;
      this._getStartBeams = null;
      this._updateBeam = null;
      this._forward = null;
      if (modelType === MODEL_TYPES.DecoderOnly) {
        this.can_generate = true;
        this._runBeam = decoderRunBeam;
        this._getStartBeams = decoderStartBeams;
        this._updateBeam = decoderUpdatebeam;
        this._forward = decoderForward;
      } else if (modelType === MODEL_TYPES.Seq2Seq || modelType === MODEL_TYPES.Vision2Seq) {
        this.can_generate = true;
        this._runBeam = seq2seqRunBeam;
        this._getStartBeams = seq2seqStartBeams;
        this._updateBeam = seq2seqUpdatebeam;
        this._forward = seq2seqForward;
      } else if (modelType === MODEL_TYPES.EncoderDecoder) {
        this._forward = encoderForward;
      } else {
        this._forward = encoderForward;
      }
    }
    /**
    * Disposes of all the ONNX sessions that were created during inference.
    * @returns {Promise<unknown[]>} An array of promises, one for each ONNX session that is being disposed.
    * @todo Use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry
    */
    dispose() {
      return __async(this, null, function* () {
        const promises = [];
        for (let key of Object.keys(this)) {
          const item = this[key];
          if (item instanceof InferenceSession) {
            promises.push(item.handler.dispose());
          }
        }
        return yield Promise.all(promises);
      });
    }
    /**
     * Instantiate one of the model classes of the library from a pretrained model.
     * 
     * The model class to instantiate is selected based on the `model_type` property of the config object
     * (either passed as an argument or loaded from `pretrained_model_name_or_path` if possible)
     * 
     * @param {string} pretrained_model_name_or_path The name or path of the pretrained model. Can be either:
     * - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
     *   Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a
     *   user or organization name, like `dbmdz/bert-base-german-cased`.
     * - A path to a *directory* containing model weights, e.g., `./my_model_directory/`.
     * @param {import('./utils/hub.js').PretrainedOptions} options Additional options for loading the model.
     * 
     * @returns {Promise<PreTrainedModel>} A new instance of the `PreTrainedModel` class.
     */
    static from_pretrained(_0) {
      return __async(this, arguments, function* (pretrained_model_name_or_path, {
        quantized = true,
        progress_callback = null,
        config: config2 = null,
        cache_dir = null,
        local_files_only = false,
        revision = "main",
        model_file_name = null
      } = {}) {
        var _a3, _b2;
        let options = {
          quantized,
          progress_callback,
          config: config2,
          cache_dir,
          local_files_only,
          revision,
          model_file_name
        };
        const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this);
        const modelType = MODEL_TYPE_MAPPING.get(modelName);
        let info;
        if (modelType === MODEL_TYPES.DecoderOnly) {
          info = yield Promise.all([
            AutoConfig.from_pretrained(pretrained_model_name_or_path, options),
            constructSession(pretrained_model_name_or_path, (_a3 = options.model_file_name) != null ? _a3 : "decoder_model_merged", options),
            getModelJSON(pretrained_model_name_or_path, "generation_config.json", false, options)
          ]);
        } else if (modelType === MODEL_TYPES.Seq2Seq || modelType === MODEL_TYPES.Vision2Seq) {
          info = yield Promise.all([
            AutoConfig.from_pretrained(pretrained_model_name_or_path, options),
            constructSession(pretrained_model_name_or_path, "encoder_model", options),
            constructSession(pretrained_model_name_or_path, "decoder_model_merged", options),
            getModelJSON(pretrained_model_name_or_path, "generation_config.json", false, options)
          ]);
        } else if (modelType === MODEL_TYPES.MaskGeneration) {
          info = yield Promise.all([
            AutoConfig.from_pretrained(pretrained_model_name_or_path, options),
            constructSession(pretrained_model_name_or_path, "vision_encoder", options),
            constructSession(pretrained_model_name_or_path, "prompt_encoder_mask_decoder", options)
          ]);
        } else if (modelType === MODEL_TYPES.EncoderDecoder) {
          info = yield Promise.all([
            AutoConfig.from_pretrained(pretrained_model_name_or_path, options),
            constructSession(pretrained_model_name_or_path, "encoder_model", options),
            constructSession(pretrained_model_name_or_path, "decoder_model_merged", options)
          ]);
        } else {
          if (modelType !== MODEL_TYPES.EncoderOnly) {
            console.warn(`Model type for '${modelName != null ? modelName : config2 == null ? void 0 : config2.model_type}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`);
          }
          info = yield Promise.all([
            AutoConfig.from_pretrained(pretrained_model_name_or_path, options),
            constructSession(pretrained_model_name_or_path, (_b2 = options.model_file_name) != null ? _b2 : "model", options)
          ]);
        }
        return new this(...info);
      });
    }
    /**
     * Runs the model with the provided inputs
     * @param {Object} model_inputs Object containing input tensors
     * @returns {Promise<Object>} Object containing output tensors
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return yield this.forward(model_inputs);
      });
    }
    /**
     * Forward method for a pretrained model. If not overridden by a subclass, the correct forward method
     * will be chosen based on the model type.
     * @param {Object} model_inputs The input data to the model in the format specified in the ONNX model.
     * @returns {Promise<Object>} The output data from the model in the format specified in the ONNX model.
     * @throws {Error} This method must be implemented in subclasses.
     */
    forward(model_inputs) {
      return __async(this, null, function* () {
        return yield this._forward(this, model_inputs);
      });
    }
    /**
     * @param {import('./utils/generation.js').GenerationConfigType} generation_config 
     * @param {number} input_ids_seq_length The starting sequence length for the input ids.
     * @returns {LogitsProcessorList}
     * @private
     */
    _get_logits_processor(generation_config, input_ids_seq_length, logits_processor = null) {
      const processors = new LogitsProcessorList();
      if (generation_config.repetition_penalty !== null && generation_config.repetition_penalty !== 1) {
        processors.push(new RepetitionPenaltyLogitsProcessor(generation_config.repetition_penalty));
      }
      if (generation_config.no_repeat_ngram_size !== null && generation_config.no_repeat_ngram_size > 0) {
        processors.push(new NoRepeatNGramLogitsProcessor(generation_config.no_repeat_ngram_size));
      }
      if (generation_config.bad_words_ids !== null) {
        processors.push(new NoBadWordsLogitsProcessor(generation_config.bad_words_ids, generation_config.eos_token_id));
      }
      if (generation_config.min_length !== null && generation_config.eos_token_id !== null && generation_config.min_length > 0) {
        processors.push(new MinLengthLogitsProcessor(generation_config.min_length, generation_config.eos_token_id));
      }
      if (generation_config.min_new_tokens !== null && generation_config.eos_token_id !== null && generation_config.min_new_tokens > 0) {
        processors.push(new MinNewTokensLengthLogitsProcessor(
          input_ids_seq_length,
          generation_config.min_new_tokens,
          generation_config.eos_token_id
        ));
      }
      if (generation_config.forced_bos_token_id !== null) {
        processors.push(new ForcedBOSTokenLogitsProcessor(generation_config.forced_bos_token_id));
      }
      if (generation_config.forced_eos_token_id !== null) {
        processors.push(new ForcedEOSTokenLogitsProcessor(
          generation_config.max_length,
          generation_config.forced_eos_token_id
        ));
      }
      if (generation_config.begin_suppress_tokens !== null) {
        let begin_index = input_ids_seq_length > 1 || generation_config.forced_bos_token_id === null ? input_ids_seq_length : input_ids_seq_length + 1;
        if (generation_config.forced_decoder_ids !== null) {
          begin_index += generation_config.forced_decoder_ids[generation_config.forced_decoder_ids.length - 1][0];
        }
        processors.push(new SuppressTokensAtBeginLogitsProcessor(generation_config.begin_suppress_tokens, begin_index));
      }
      if (generation_config.forced_decoder_ids !== null) {
        processors.push(new ForceTokensLogitsProcessor(generation_config.forced_decoder_ids));
      }
      if (logits_processor !== null) {
        processors.extend(logits_processor);
      }
      return processors;
    }
    /**
     * This function merges multiple generation configs together to form a final generation config to be used by the model for text generation.
     * It first creates an empty `GenerationConfig` object, then it applies the model's own `generation_config` property to it. Finally, if a `generation_config` object was passed in the arguments, it overwrites the corresponding properties in the final config with those of the passed config object.
     * @param {import('./utils/generation.js').GenerationConfigType} generation_config A `GenerationConfig` object containing generation parameters.
     * @returns {import('./utils/generation.js').GenerationConfigType} The final generation config object to be used by the model for text generation.
     */
    _get_generation_config(generation_config) {
      let gen_config = new GenerationConfig(this.config);
      if ("generation_config" in this) {
        Object.assign(gen_config, this.generation_config);
      }
      if (generation_config !== null) {
        Object.assign(gen_config, generation_config);
      }
      return gen_config;
    }
    /**
     * @typedef {import('./utils/maths.js').TypedArray} TypedArray
     */
    /**
     * @typedef {{ sequences: Tensor, decoder_attentions: Tensor, cross_attentions: Tensor }} EncoderDecoderOutput
     * @typedef {Object} DecoderOutput
     * 
     * Generates text based on the given inputs and generation configuration using the model.
     * @param {Tensor|Array|TypedArray} inputs An array of input token IDs.
     * @param {Object|GenerationConfig|null} generation_config The generation configuration to use. If null, default configuration will be used.
     * @param {Object|null} logits_processor An optional logits processor to use. If null, a new LogitsProcessorList instance will be created.
     * @param {Object} options options
     * @param {Object} [options.inputs_attention_mask=null] An optional attention mask for the inputs.
     * @returns {Promise<number[][]|EncoderDecoderOutput|DecoderOutput>} An array of generated output sequences, where each sequence is an array of token IDs.
     * @throws {Error} Throws an error if the inputs array is empty.
     */
    generate(_0) {
      return __async(this, arguments, function* (inputs, generation_config = null, logits_processor = null, {
        inputs_attention_mask = null
      } = {}) {
        var _a3, _b2, _c2, _d2, _e;
        if (!this.can_generate) {
          const modelName = MODEL_CLASS_TO_NAME_MAPPING.get(this.constructor);
          let errorMessage = `The current model class (${modelName}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;
          const modelType = this.config.model_type;
          const possibleInfo = (_c2 = (_b2 = (_a3 = MODEL_WITH_LM_HEAD_MAPPING_NAMES.get(modelType)) != null ? _a3 : MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES.get(modelType)) != null ? _b2 : MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES.get(modelType)) != null ? _c2 : MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES.get(modelType);
          if (possibleInfo) {
            errorMessage += ` Please use the following class instead: '${possibleInfo[0]}'`;
          }
          throw Error(errorMessage);
        }
        if (!(inputs instanceof Tensor) && !isTypedArray(inputs) && !Array.isArray(inputs)) {
          throw Error(`\`inputs\` must be a Tensor, TypedArray, or Array, but is "${inputs.constructor.name}".`);
        }
        let input_ids_seq_length;
        if (this.config.is_encoder_decoder) {
          input_ids_seq_length = 0;
        } else {
          input_ids_seq_length = inputs instanceof Tensor ? inputs.dims.at(-1) : inputs.length;
          if (input_ids_seq_length === 0) {
            throw Error("Must supply a non-empty array of input token ids.");
          }
        }
        generation_config = this._get_generation_config(generation_config);
        logits_processor = logits_processor != null ? logits_processor : new LogitsProcessorList();
        logits_processor = this._get_logits_processor(
          generation_config,
          input_ids_seq_length,
          logits_processor
        );
        let eos_token_ids = generation_config.eos_token_id;
        if (eos_token_ids !== null && !Array.isArray(eos_token_ids)) {
          eos_token_ids = [eos_token_ids];
        }
        let numOutputTokens = 1;
        const maxOutputTokens = numOutputTokens + ((_d2 = generation_config.max_new_tokens) != null ? _d2 : Infinity);
        const useMaxLength = Number.isInteger(generation_config.max_length) && ((_e = generation_config.max_new_tokens) != null ? _e : null) === null;
        let sampler = Sampler.getSampler(generation_config);
        let beams = this.getStartBeams(inputs, generation_config, numOutputTokens, inputs_attention_mask);
        while (beams.some((x) => !x.done) && numOutputTokens < maxOutputTokens) {
          let newest_beams = [];
          for (let beam of beams) {
            if (beam.done) {
              newest_beams.push(beam);
              continue;
            }
            if (useMaxLength && beam.output_token_ids.length >= generation_config.max_length) {
              beam.done = true;
              newest_beams.push(beam);
              continue;
            }
            let output = yield this.runBeam(beam);
            if (generation_config.output_attentions) {
              this.addAttentionsToBeam(beam, output);
            }
            if (generation_config.output_scores) ;
            let logits = output.logits.slice(null, -1, null);
            logits_processor(beam.output_token_ids, logits);
            let sampledTokens = sampler(logits);
            for (let [newTokenId, logProb] of sampledTokens) {
              let newBeam = __spreadValues({}, beam);
              this.updateBeam(newBeam, newTokenId);
              newBeam.score += logProb;
              if (eos_token_ids && eos_token_ids.includes(newTokenId)) {
                newBeam.done = true;
              }
              newest_beams.push(newBeam);
            }
          }
          ++numOutputTokens;
          newest_beams = this.groupBeams(newest_beams).map(
            (group) => group.sort((a, b) => b.score - a.score).slice(0, generation_config.num_beams)
            // remove outside beam width
          );
          beams = newest_beams.flat();
          if (generation_config.callback_function) {
            generation_config.callback_function(beams);
          }
        }
        const groupedBeams = this.groupBeams(beams);
        const getFlattened = (key) => groupedBeams.map(
          (batch) => {
            if (generation_config.num_return_sequences > 1) {
              return batch.slice(0, generation_config.num_return_sequences).map((x) => x[key]);
            } else {
              return [batch[0][key]];
            }
          }
        ).flat();
        const sequences = getFlattened("output_token_ids");
        if (generation_config.return_dict_in_generate) {
          const decoder_attentions = getFlattened("decoder_attentions");
          const cross_attentions = getFlattened("cross_attentions");
          return {
            sequences,
            decoder_attentions,
            cross_attentions
          };
        } else {
          return sequences;
        }
      });
    }
    /**
     * Helper function to add attentions to beam
     * @param {Object} beam 
     * @param {Object} output
     * @private 
     */
    addAttentionsToBeam(beam, output) {
      if (this.config.is_encoder_decoder) {
        if (!output.cross_attentions || output.cross_attentions.length === 0) {
          throw Error(
            "`output_attentions` is true, but the model did not produce cross-attentions. This is most likely because the model was not exported with `output_attentions=True`."
          );
        }
        if (!beam.cross_attentions) {
          beam.cross_attentions = [];
        }
        beam.cross_attentions.push(output.cross_attentions);
      }
      if (!output.decoder_attentions || output.decoder_attentions.length === 0) {
        throw Error(
          "`output_attentions` is true, but the model did not produce decoder-attentions. This is most likely because the model was not exported with `output_attentions=True`."
        );
      }
      if (!beam.decoder_attentions) {
        beam.decoder_attentions = [];
      }
      beam.decoder_attentions.push(output.decoder_attentions);
    }
    /**
     * Groups an array of beam objects by their ids.
     *
     * @param {Array} beams The array of beam objects to group.
     * @returns {Array} An array of arrays, where each inner array contains beam objects with the same id.
     */
    groupBeams(beams) {
      const groups = /* @__PURE__ */ Object.create(null);
      for (const obj of beams) {
        if (groups[obj.id] === void 0) {
          groups[obj.id] = [obj];
        } else {
          groups[obj.id].push(obj);
        }
      }
      return Object.values(groups);
    }
    /**
     * Returns an object containing past key values from the given decoder results object.
     *
     * @param {Object} decoderResults The decoder results object.
     * @param {Object} pastKeyValues The previous past key values.
     * @returns {Object} An object containing past key values.
     */
    getPastKeyValues(decoderResults, pastKeyValues) {
      const pkvs = /* @__PURE__ */ Object.create(null);
      for (const name2 in decoderResults) {
        if (name2.startsWith("present")) {
          let newName = name2.replace("present", "past_key_values");
          if (pastKeyValues && name2.includes("encoder")) {
            pkvs[newName] = pastKeyValues[newName];
          } else {
            pkvs[newName] = decoderResults[name2];
          }
        }
      }
      return pkvs;
    }
    /**
     * Returns an object containing attentions from the given decoder results object.
     *
     * @param {Object} decoderResults The decoder results object.
     * @returns {Object} An object containing attentions.
     */
    getAttentions(decoderResults) {
      const attns = /* @__PURE__ */ Object.create(null);
      for (const attnName of ["cross_attentions", "decoder_attentions"]) {
        const result2 = [];
        for (const name2 in decoderResults) {
          if (name2.startsWith(attnName)) {
            const index2 = name2.split(".").pop();
            result2[index2] = decoderResults[name2];
          }
        }
        attns[attnName] = result2;
      }
      return attns;
    }
    /**
     * Adds past key values to the decoder feeds object. If pastKeyValues is null, creates new tensors for past key values.
     *
     * @param {Object} decoderFeeds The decoder feeds object to add past key values to.
     * @param {Object} pastKeyValues An object containing past key values.
     */
    addPastKeyValues(decoderFeeds, pastKeyValues) {
      var _a3;
      if (pastKeyValues) {
        Object.assign(decoderFeeds, pastKeyValues);
      } else {
        const batch_size = 1;
        if (this.config.is_encoder_decoder && ((_a3 = this.add_encoder_pkv) != null ? _a3 : true)) {
          let encoder_dims = [batch_size, this.num_encoder_heads, 0, this.encoder_dim_kv];
          let decoder_dims = [batch_size, this.num_decoder_heads, 0, this.decoder_dim_kv];
          for (let i2 = 0; i2 < this.num_decoder_layers; ++i2) {
            decoderFeeds[`past_key_values.${i2}.encoder.key`] = new Tensor("float32", [], encoder_dims);
            decoderFeeds[`past_key_values.${i2}.encoder.value`] = new Tensor("float32", [], encoder_dims);
            decoderFeeds[`past_key_values.${i2}.decoder.key`] = new Tensor("float32", [], decoder_dims);
            decoderFeeds[`past_key_values.${i2}.decoder.value`] = new Tensor("float32", [], decoder_dims);
          }
        } else if (this.config.model_type === "falcon") {
          let dims = [batch_size * this.num_heads, 0, this.dim_kv];
          for (let i2 = 0; i2 < this.num_layers; ++i2) {
            decoderFeeds[`past_key_values.${i2}.key`] = new Tensor("float32", [], dims);
            decoderFeeds[`past_key_values.${i2}.value`] = new Tensor("float32", [], dims);
          }
        } else if (this.config.multi_query) {
          let dims = [batch_size * this.num_heads, 0, 2 * this.dim_kv];
          for (let i2 = 0; i2 < this.num_layers; ++i2) {
            decoderFeeds[`past_key_values.${i2}.key_value`] = new Tensor("float32", [], dims);
          }
        } else if (this.config.model_type === "bloom") {
          let keyDims = [batch_size * this.num_heads, this.dim_kv, 0];
          let valueDims = [batch_size * this.num_heads, 0, this.dim_kv];
          for (let i2 = 0; i2 < this.num_layers; ++i2) {
            decoderFeeds[`past_key_values.${i2}.key`] = new Tensor("float32", [], keyDims);
            decoderFeeds[`past_key_values.${i2}.value`] = new Tensor("float32", [], valueDims);
          }
        } else {
          let dims = [batch_size, this.num_heads, 0, this.dim_kv];
          for (let i2 = 0; i2 < this.num_layers; ++i2) {
            decoderFeeds[`past_key_values.${i2}.key`] = new Tensor("float32", [], dims);
            decoderFeeds[`past_key_values.${i2}.value`] = new Tensor("float32", [], dims);
          }
        }
      }
    }
    /**
     * Initializes and returns the beam for text generation task
     * @param {Tensor} inputTokenIds The input token ids.
     * @param {Object} generation_config The generation config.
     * @param {number} numOutputTokens The number of tokens to be generated.
     * @param {Tensor} inputs_attention_mask Optional input attention mask.
     * @returns {any} A Beam object representing the initialized beam.
     * @private
     */
    getStartBeams(inputTokenIds, generation_config, numOutputTokens, inputs_attention_mask) {
      return this._getStartBeams(this, inputTokenIds, generation_config, numOutputTokens, inputs_attention_mask);
    }
    /**
     * Runs a single step of the beam search generation algorithm.
     * @param {any} beam The current beam being generated.
     * @returns {Promise<any>} The updated beam after a single generation step.
     * @private
     */
    runBeam(beam) {
      return __async(this, null, function* () {
        return yield this._runBeam(this, beam);
      });
    }
    /**
     * Update a beam with a new token ID.
     * @param {Object} beam The beam to update.
     * @param {number} newTokenId The new token ID to add to the beam's output.
     * @private
     */
    updateBeam(beam, newTokenId) {
      return this._updateBeam(beam, newTokenId);
    }
  }
  class ModelOutput {
  }
  class BertPreTrainedModel extends PreTrainedModel {
  }
  class BertModel extends BertPreTrainedModel {
  }
  class BertForMaskedLM extends BertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new MaskedLMOutput(yield __superGet(BertForMaskedLM.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class BertForSequenceClassification extends BertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new SequenceClassifierOutput(yield __superGet(BertForSequenceClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class BertForTokenClassification extends BertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new TokenClassifierOutput(yield __superGet(BertForTokenClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class BertForQuestionAnswering extends BertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new QuestionAnsweringModelOutput(yield __superGet(BertForQuestionAnswering.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class NomicBertPreTrainedModel extends PreTrainedModel {
  }
  class NomicBertModel extends NomicBertPreTrainedModel {
  }
  class RoFormerPreTrainedModel extends PreTrainedModel {
  }
  class RoFormerModel extends RoFormerPreTrainedModel {
  }
  class RoFormerForMaskedLM extends RoFormerPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new MaskedLMOutput(yield __superGet(RoFormerForMaskedLM.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class RoFormerForSequenceClassification extends RoFormerPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new SequenceClassifierOutput(yield __superGet(RoFormerForSequenceClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class RoFormerForTokenClassification extends RoFormerPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new TokenClassifierOutput(yield __superGet(RoFormerForTokenClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class RoFormerForQuestionAnswering extends RoFormerPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new QuestionAnsweringModelOutput(yield __superGet(RoFormerForQuestionAnswering.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class ConvBertPreTrainedModel extends PreTrainedModel {
  }
  class ConvBertModel extends ConvBertPreTrainedModel {
  }
  class ConvBertForMaskedLM extends ConvBertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new MaskedLMOutput(yield __superGet(ConvBertForMaskedLM.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class ConvBertForSequenceClassification extends ConvBertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new SequenceClassifierOutput(yield __superGet(ConvBertForSequenceClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class ConvBertForTokenClassification extends ConvBertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new TokenClassifierOutput(yield __superGet(ConvBertForTokenClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class ConvBertForQuestionAnswering extends ConvBertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new QuestionAnsweringModelOutput(yield __superGet(ConvBertForQuestionAnswering.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class ElectraPreTrainedModel extends PreTrainedModel {
  }
  class ElectraModel extends ElectraPreTrainedModel {
  }
  class ElectraForMaskedLM extends ElectraPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new MaskedLMOutput(yield __superGet(ElectraForMaskedLM.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class ElectraForSequenceClassification extends ElectraPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new SequenceClassifierOutput(yield __superGet(ElectraForSequenceClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class ElectraForTokenClassification extends ElectraPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new TokenClassifierOutput(yield __superGet(ElectraForTokenClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class ElectraForQuestionAnswering extends ElectraPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new QuestionAnsweringModelOutput(yield __superGet(ElectraForQuestionAnswering.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class CamembertPreTrainedModel extends PreTrainedModel {
  }
  class CamembertModel extends CamembertPreTrainedModel {
  }
  class CamembertForMaskedLM extends CamembertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new MaskedLMOutput(yield __superGet(CamembertForMaskedLM.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class CamembertForSequenceClassification extends CamembertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new SequenceClassifierOutput(yield __superGet(CamembertForSequenceClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class CamembertForTokenClassification extends CamembertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new TokenClassifierOutput(yield __superGet(CamembertForTokenClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class CamembertForQuestionAnswering extends CamembertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new QuestionAnsweringModelOutput(yield __superGet(CamembertForQuestionAnswering.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class DebertaPreTrainedModel extends PreTrainedModel {
  }
  class DebertaModel extends DebertaPreTrainedModel {
  }
  class DebertaForMaskedLM extends DebertaPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new MaskedLMOutput(yield __superGet(DebertaForMaskedLM.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class DebertaForSequenceClassification extends DebertaPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new SequenceClassifierOutput(yield __superGet(DebertaForSequenceClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class DebertaForTokenClassification extends DebertaPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new TokenClassifierOutput(yield __superGet(DebertaForTokenClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class DebertaForQuestionAnswering extends DebertaPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new QuestionAnsweringModelOutput(yield __superGet(DebertaForQuestionAnswering.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class DebertaV2PreTrainedModel extends PreTrainedModel {
  }
  class DebertaV2Model extends DebertaV2PreTrainedModel {
  }
  class DebertaV2ForMaskedLM extends DebertaV2PreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new MaskedLMOutput(yield __superGet(DebertaV2ForMaskedLM.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class DebertaV2ForSequenceClassification extends DebertaV2PreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new SequenceClassifierOutput(yield __superGet(DebertaV2ForSequenceClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class DebertaV2ForTokenClassification extends DebertaV2PreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new TokenClassifierOutput(yield __superGet(DebertaV2ForTokenClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class DebertaV2ForQuestionAnswering extends DebertaV2PreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new QuestionAnsweringModelOutput(yield __superGet(DebertaV2ForQuestionAnswering.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class DistilBertPreTrainedModel extends PreTrainedModel {
  }
  class DistilBertModel extends DistilBertPreTrainedModel {
  }
  class DistilBertForSequenceClassification extends DistilBertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new SequenceClassifierOutput(yield __superGet(DistilBertForSequenceClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class DistilBertForTokenClassification extends DistilBertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new TokenClassifierOutput(yield __superGet(DistilBertForTokenClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class DistilBertForQuestionAnswering extends DistilBertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new QuestionAnsweringModelOutput(yield __superGet(DistilBertForQuestionAnswering.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class DistilBertForMaskedLM extends DistilBertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<MaskedLMOutput>} returned object
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new MaskedLMOutput(yield __superGet(DistilBertForMaskedLM.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class EsmPreTrainedModel extends PreTrainedModel {
  }
  class EsmModel extends EsmPreTrainedModel {
  }
  class EsmForMaskedLM extends EsmPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new MaskedLMOutput(yield __superGet(EsmForMaskedLM.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class EsmForSequenceClassification extends EsmPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new SequenceClassifierOutput(yield __superGet(EsmForSequenceClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class EsmForTokenClassification extends EsmPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new TokenClassifierOutput(yield __superGet(EsmForTokenClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class MobileBertPreTrainedModel extends PreTrainedModel {
  }
  class MobileBertModel extends MobileBertPreTrainedModel {
  }
  class MobileBertForMaskedLM extends MobileBertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<MaskedLMOutput>} returned object
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new MaskedLMOutput(yield __superGet(MobileBertForMaskedLM.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class MobileBertForSequenceClassification extends MobileBertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} returned object
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new SequenceClassifierOutput(yield __superGet(MobileBertForSequenceClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class MobileBertForQuestionAnswering extends MobileBertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<QuestionAnsweringModelOutput>} returned object
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new QuestionAnsweringModelOutput(yield __superGet(MobileBertForQuestionAnswering.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class MPNetPreTrainedModel extends PreTrainedModel {
  }
  class MPNetModel extends MPNetPreTrainedModel {
  }
  class MPNetForMaskedLM extends MPNetPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<MaskedLMOutput>} An object containing the model's output logits for masked language modeling.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new MaskedLMOutput(yield __superGet(MPNetForMaskedLM.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class MPNetForSequenceClassification extends MPNetPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new SequenceClassifierOutput(yield __superGet(MPNetForSequenceClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class MPNetForTokenClassification extends MPNetPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new TokenClassifierOutput(yield __superGet(MPNetForTokenClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class MPNetForQuestionAnswering extends MPNetPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<QuestionAnsweringModelOutput>} An object containing the model's output logits for question answering.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new QuestionAnsweringModelOutput(yield __superGet(MPNetForQuestionAnswering.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class SqueezeBertPreTrainedModel extends PreTrainedModel {
  }
  class SqueezeBertModel extends SqueezeBertPreTrainedModel {
  }
  class SqueezeBertForMaskedLM extends SqueezeBertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<MaskedLMOutput>} returned object
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new MaskedLMOutput(yield __superGet(SqueezeBertForMaskedLM.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class SqueezeBertForSequenceClassification extends SqueezeBertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} returned object
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new SequenceClassifierOutput(yield __superGet(SqueezeBertForSequenceClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class SqueezeBertForQuestionAnswering extends SqueezeBertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<QuestionAnsweringModelOutput>} returned object
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new QuestionAnsweringModelOutput(yield __superGet(SqueezeBertForQuestionAnswering.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class AlbertPreTrainedModel extends PreTrainedModel {
  }
  class AlbertModel extends AlbertPreTrainedModel {
  }
  class AlbertForSequenceClassification extends AlbertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} returned object
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new SequenceClassifierOutput(yield __superGet(AlbertForSequenceClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class AlbertForQuestionAnswering extends AlbertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<QuestionAnsweringModelOutput>} returned object
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new QuestionAnsweringModelOutput(yield __superGet(AlbertForQuestionAnswering.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class AlbertForMaskedLM extends AlbertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<MaskedLMOutput>} returned object
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new MaskedLMOutput(yield __superGet(AlbertForMaskedLM.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class T5PreTrainedModel extends PreTrainedModel {
  }
  class T5Model extends T5PreTrainedModel {
  }
  class T5ForConditionalGeneration extends T5PreTrainedModel {
    /**
     * Creates a new instance of the `T5ForConditionalGeneration` class.
     * @param {Object} config The model configuration.
     * @param {any} session session for the model.
     * @param {any} decoder_merged_session session for the decoder.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config2, session, decoder_merged_session, generation_config) {
      super(config2, session);
      this.decoder_merged_session = decoder_merged_session;
      this.generation_config = generation_config;
      this.num_decoder_layers = this.config.num_decoder_layers;
      this.num_decoder_heads = this.config.num_heads;
      this.decoder_dim_kv = this.config.d_kv;
      this.num_encoder_layers = this.config.num_layers;
      this.num_encoder_heads = this.config.num_heads;
      this.encoder_dim_kv = this.config.d_kv;
    }
  }
  class LongT5PreTrainedModel extends PreTrainedModel {
  }
  class LongT5Model extends LongT5PreTrainedModel {
  }
  class LongT5ForConditionalGeneration extends LongT5PreTrainedModel {
    /**
     * Creates a new instance of the `LongT5ForConditionalGeneration` class.
     * @param {Object} config The model configuration.
     * @param {any} session session for the model.
     * @param {any} decoder_merged_session session for the decoder.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config2, session, decoder_merged_session, generation_config) {
      super(config2, session);
      this.decoder_merged_session = decoder_merged_session;
      this.generation_config = generation_config;
      this.num_decoder_layers = this.config.num_decoder_layers;
      this.num_decoder_heads = this.config.num_heads;
      this.decoder_dim_kv = this.config.d_kv;
      this.num_encoder_layers = this.config.num_layers;
      this.num_encoder_heads = this.config.num_heads;
      this.encoder_dim_kv = this.config.d_kv;
    }
  }
  class MT5PreTrainedModel extends PreTrainedModel {
  }
  class MT5Model extends MT5PreTrainedModel {
  }
  class MT5ForConditionalGeneration extends MT5PreTrainedModel {
    /**
     * Creates a new instance of the `MT5ForConditionalGeneration` class.
     * @param {any} config The model configuration.
     * @param {any} session The ONNX session containing the encoder weights.
     * @param {any} decoder_merged_session The ONNX session containing the merged decoder weights.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config2, session, decoder_merged_session, generation_config) {
      super(config2, session);
      this.decoder_merged_session = decoder_merged_session;
      this.generation_config = generation_config;
      this.num_decoder_layers = this.config.num_decoder_layers;
      this.num_decoder_heads = this.config.num_heads;
      this.decoder_dim_kv = this.config.d_kv;
      this.num_encoder_layers = this.config.num_layers;
      this.num_encoder_heads = this.config.num_heads;
      this.encoder_dim_kv = this.config.d_kv;
    }
  }
  class BartPretrainedModel extends PreTrainedModel {
  }
  class BartModel extends BartPretrainedModel {
  }
  class BartForConditionalGeneration extends BartPretrainedModel {
    /**
     * Creates a new instance of the `BartForConditionalGeneration` class.
     * @param {Object} config The configuration object for the Bart model.
     * @param {Object} session The ONNX session used to execute the model.
     * @param {Object} decoder_merged_session The ONNX session used to execute the decoder.
     * @param {Object} generation_config The generation configuration object.
     */
    constructor(config2, session, decoder_merged_session, generation_config) {
      super(config2, session);
      this.decoder_merged_session = decoder_merged_session;
      this.generation_config = generation_config;
      this.num_decoder_layers = this.config.decoder_layers;
      this.num_decoder_heads = this.config.decoder_attention_heads;
      this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads;
      this.num_encoder_layers = this.config.encoder_layers;
      this.num_encoder_heads = this.config.encoder_attention_heads;
      this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads;
    }
  }
  class BartForSequenceClassification extends BartPretrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new SequenceClassifierOutput(yield __superGet(BartForSequenceClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class MBartPreTrainedModel extends PreTrainedModel {
  }
  class MBartModel extends MBartPreTrainedModel {
  }
  class MBartForConditionalGeneration extends MBartPreTrainedModel {
    /**
     * Creates a new instance of the `MBartForConditionalGeneration` class.
     * @param {Object} config The configuration object for the Bart model.
     * @param {Object} session The ONNX session used to execute the model.
     * @param {Object} decoder_merged_session The ONNX session used to execute the decoder.
     * @param {Object} generation_config The generation configuration object.
     */
    constructor(config2, session, decoder_merged_session, generation_config) {
      super(config2, session);
      this.decoder_merged_session = decoder_merged_session;
      this.generation_config = generation_config;
      this.num_decoder_layers = this.config.decoder_layers;
      this.num_decoder_heads = this.config.decoder_attention_heads;
      this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads;
      this.num_encoder_layers = this.config.encoder_layers;
      this.num_encoder_heads = this.config.encoder_attention_heads;
      this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads;
    }
  }
  class MBartForSequenceClassification extends MBartPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new SequenceClassifierOutput(yield __superGet(MBartForSequenceClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class MBartForCausalLM extends MBartPreTrainedModel {
    /**
     * Creates a new instance of the `MBartForCausalLM` class.
     * @param {Object} config Configuration object for the model.
     * @param {Object} decoder_merged_session ONNX Session object for the decoder.
     * @param {Object} generation_config Configuration object for the generation process.
     */
    constructor(config2, decoder_merged_session, generation_config) {
      super(config2, decoder_merged_session);
      this.generation_config = generation_config;
      this.num_decoder_layers = this.config.decoder_layers;
      this.num_decoder_heads = this.config.decoder_attention_heads;
      this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads;
      this.num_encoder_layers = this.config.encoder_layers;
      this.num_encoder_heads = this.config.encoder_attention_heads;
      this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads;
    }
  }
  class BlenderbotPreTrainedModel extends PreTrainedModel {
  }
  class BlenderbotModel extends BlenderbotPreTrainedModel {
  }
  class BlenderbotForConditionalGeneration extends BlenderbotPreTrainedModel {
    /**
     * Creates a new instance of the `BlenderbotForConditionalGeneration` class.
     * @param {any} config The model configuration.
     * @param {any} session The ONNX session containing the encoder weights.
     * @param {any} decoder_merged_session The ONNX session containing the merged decoder weights.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config2, session, decoder_merged_session, generation_config) {
      super(config2, session);
      this.decoder_merged_session = decoder_merged_session;
      this.generation_config = generation_config;
      this.num_decoder_layers = this.config.decoder_layers;
      this.num_decoder_heads = this.config.decoder_attention_heads;
      this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads;
      this.num_encoder_layers = this.config.encoder_layers;
      this.num_encoder_heads = this.config.encoder_attention_heads;
      this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads;
    }
  }
  class BlenderbotSmallPreTrainedModel extends PreTrainedModel {
  }
  class BlenderbotSmallModel extends BlenderbotSmallPreTrainedModel {
  }
  class BlenderbotSmallForConditionalGeneration extends BlenderbotSmallPreTrainedModel {
    /**
     * Creates a new instance of the `BlenderbotForConditionalGeneration` class.
     * @param {any} config The model configuration.
     * @param {any} session The ONNX session containing the encoder weights.
     * @param {any} decoder_merged_session The ONNX session containing the merged decoder weights.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config2, session, decoder_merged_session, generation_config) {
      super(config2, session);
      this.decoder_merged_session = decoder_merged_session;
      this.generation_config = generation_config;
      this.num_decoder_layers = this.config.decoder_layers;
      this.num_decoder_heads = this.config.decoder_attention_heads;
      this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads;
      this.num_encoder_layers = this.config.encoder_layers;
      this.num_encoder_heads = this.config.encoder_attention_heads;
      this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads;
    }
  }
  class RobertaPreTrainedModel extends PreTrainedModel {
  }
  class RobertaModel extends RobertaPreTrainedModel {
  }
  class RobertaForMaskedLM extends RobertaPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<MaskedLMOutput>} returned object
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new MaskedLMOutput(yield __superGet(RobertaForMaskedLM.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class RobertaForSequenceClassification extends RobertaPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} returned object
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new SequenceClassifierOutput(yield __superGet(RobertaForSequenceClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class RobertaForTokenClassification extends RobertaPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new TokenClassifierOutput(yield __superGet(RobertaForTokenClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class RobertaForQuestionAnswering extends RobertaPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<QuestionAnsweringModelOutput>} returned object
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new QuestionAnsweringModelOutput(yield __superGet(RobertaForQuestionAnswering.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class XLMPreTrainedModel extends PreTrainedModel {
  }
  class XLMModel extends XLMPreTrainedModel {
  }
  class XLMWithLMHeadModel extends XLMPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<MaskedLMOutput>} returned object
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new MaskedLMOutput(yield __superGet(XLMWithLMHeadModel.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class XLMForSequenceClassification extends XLMPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} returned object
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new SequenceClassifierOutput(yield __superGet(XLMForSequenceClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class XLMForTokenClassification extends XLMPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new TokenClassifierOutput(yield __superGet(XLMForTokenClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class XLMForQuestionAnswering extends XLMPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<QuestionAnsweringModelOutput>} returned object
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new QuestionAnsweringModelOutput(yield __superGet(XLMForQuestionAnswering.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class XLMRobertaPreTrainedModel extends PreTrainedModel {
  }
  class XLMRobertaModel extends XLMRobertaPreTrainedModel {
  }
  class XLMRobertaForMaskedLM extends XLMRobertaPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<MaskedLMOutput>} returned object
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new MaskedLMOutput(yield __superGet(XLMRobertaForMaskedLM.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class XLMRobertaForSequenceClassification extends XLMRobertaPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} returned object
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new SequenceClassifierOutput(yield __superGet(XLMRobertaForSequenceClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class XLMRobertaForTokenClassification extends XLMRobertaPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for token classification.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new TokenClassifierOutput(yield __superGet(XLMRobertaForTokenClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class XLMRobertaForQuestionAnswering extends XLMRobertaPreTrainedModel {
    /**
     * Calls the model on new inputs.
     *
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<QuestionAnsweringModelOutput>} returned object
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new QuestionAnsweringModelOutput(yield __superGet(XLMRobertaForQuestionAnswering.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class ASTPreTrainedModel extends PreTrainedModel {
  }
  class ASTModel extends ASTPreTrainedModel {
  }
  class ASTForAudioClassification extends ASTPreTrainedModel {
  }
  class WhisperPreTrainedModel extends PreTrainedModel {
  }
  class WhisperModel extends WhisperPreTrainedModel {
  }
  class WhisperForConditionalGeneration extends WhisperPreTrainedModel {
    /**
     * Creates a new instance of the `WhisperForConditionalGeneration` class.
     * @param {Object} config Configuration object for the model.
     * @param {Object} session ONNX Session object for the model.
     * @param {Object} decoder_merged_session ONNX Session object for the decoder.
     * @param {Object} generation_config Configuration object for the generation process.
     */
    constructor(config2, session, decoder_merged_session, generation_config) {
      super(config2, session);
      __publicField2(this, "requires_attention_mask", false);
      __publicField2(this, "main_input_name", "input_features");
      this.decoder_merged_session = decoder_merged_session;
      this.generation_config = generation_config;
      this.num_decoder_layers = this.config.decoder_layers;
      this.num_decoder_heads = this.config.decoder_attention_heads;
      this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads;
      this.num_encoder_layers = this.config.encoder_layers;
      this.num_encoder_heads = this.config.encoder_attention_heads;
      this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads;
    }
    /**
     * @typedef {Object} WhisperGenerationConfig
     * @extends GenerationConfig
     * @property {boolean} [return_timestamps=null] Whether to return the timestamps with the text. This enables the `WhisperTimestampsLogitsProcessor`.
     * @property {boolean} [return_token_timestamps=null] Whether to return token-level timestamps
     * with the text. This can be used with or without the `return_timestamps` option. To get word-level
     * timestamps, use the tokenizer to group the tokens into words.
     * @property {number} [num_frames=null]  The number of audio frames available in this chunk. This is only used generating word-level timestamps.
     */
    /**
     * Generates outputs based on input and generation configuration.
     * @param {Object} inputs Input data for the model.
     * @param {WhisperGenerationConfig} generation_config Configuration object for the generation process.
     * @param {Object} logits_processor Optional logits processor object.
     * @returns {Promise<Object>} Promise object represents the generated outputs.
     */
    generate(inputs, generation_config = null, logits_processor = null) {
      return __async(this, null, function* () {
        var _a3;
        generation_config = this._get_generation_config(generation_config);
        (_a3 = generation_config.return_timestamps) != null ? _a3 : generation_config.return_timestamps = false;
        if (generation_config.return_timestamps) {
          logits_processor = [new WhisperTimeStampLogitsProcessor(generation_config)];
        }
        if (generation_config.return_token_timestamps) {
          generation_config.output_attentions = true;
          generation_config.return_dict_in_generate = true;
          if (generation_config.task === "translate") {
            console.warn("Token-level timestamps may not be reliable for task 'translate'.");
          }
          if (!generation_config.alignment_heads) {
            throw new Error(
              "Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config."
            );
          }
        }
        const outputs = yield __superGet(WhisperForConditionalGeneration.prototype, this, "generate").call(this, inputs, generation_config, logits_processor);
        if (generation_config.return_token_timestamps && generation_config.alignment_heads) {
          outputs["token_timestamps"] = this._extract_token_timestamps(
            outputs,
            generation_config.alignment_heads,
            generation_config.num_frames
          );
        }
        return outputs;
      });
    }
    /**
     * Calculates token-level timestamps using the encoder-decoder cross-attentions and
     * dynamic time-warping (DTW) to map each output token to a position in the input audio.
     * @param {Object} generate_outputs Outputs generated by the model
     * @param {Tensor[][][]} generate_outputs.cross_attentions The cross attentions output by the model
     * @param {Tensor[][][]} generate_outputs.decoder_attentions The decoder attentions output by the model
     * @param {number[][]} generate_outputs.sequences The sequences output by the model
     * @param {number[][]} alignment_heads Alignment heads of the model
     * @param {number} [num_frames=null] Number of frames in the input audio.
     * @param {number} [time_precision=0.02] Precision of the timestamps in seconds
     * @returns {Tensor} tensor containing the timestamps in seconds for each predicted token
     */
    _extract_token_timestamps(generate_outputs, alignment_heads, num_frames = null, time_precision = 0.02) {
      if (!generate_outputs.cross_attentions) {
        throw new Error(
          "Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`."
        );
      }
      let median_filter_width = this.config.median_filter_width;
      if (median_filter_width === void 0) {
        console.warn("Model config has no `median_filter_width`, using default value of 7.");
        median_filter_width = 7;
      }
      const batchedMatrices = generate_outputs.cross_attentions.map((batch) => {
        let cross_attentions = Array.from(
          { length: this.config.decoder_layers },
          (_, i2) => cat(batch.map((x) => x[i2]), 2)
        );
        let weights = stack(alignment_heads.map(([l, h]) => {
          return num_frames ? cross_attentions[l].slice(null, h, null, [0, num_frames]) : cross_attentions[l].slice(null, h);
        }));
        weights = weights.transpose(1, 0, 2, 3);
        let [std, calculatedMean] = std_mean(weights, -2, 0, true);
        let smoothedWeights = weights.clone();
        for (let a = 0; a < smoothedWeights.dims[0]; ++a) {
          let aTensor = smoothedWeights[a];
          for (let b = 0; b < aTensor.dims[0]; ++b) {
            let bTensor = aTensor[b];
            const stdTensor = std[a][b][0];
            const meanTensor = calculatedMean[a][b][0];
            for (let c = 0; c < bTensor.dims[0]; ++c) {
              let cTensor = bTensor[c];
              for (let d = 0; d < cTensor.data.length; ++d) {
                cTensor.data[d] = (cTensor.data[d] - meanTensor.data[d]) / stdTensor.data[d];
              }
              cTensor.data.set(medianFilter(cTensor.data, median_filter_width));
            }
          }
        }
        const matrix = mean(smoothedWeights, 1);
        return matrix;
      });
      const timestampsShape = [generate_outputs.sequences.length, generate_outputs.sequences[0].length];
      const timestamps = new Tensor(
        "float32",
        new Float32Array(timestampsShape[0] * timestampsShape[1]),
        timestampsShape
      );
      for (let batch_idx = 0; batch_idx < timestampsShape[0]; ++batch_idx) {
        const matrix = batchedMatrices[batch_idx].neg().squeeze_(0);
        let [text_indices, time_indices] = dynamicTimeWarping(matrix);
        let diffs = Array.from({ length: text_indices.length - 1 }, (v, i2) => text_indices[i2 + 1] - text_indices[i2]);
        let jumps = mergeArrays([1], diffs).map((x) => !!x);
        let jump_times = [];
        for (let i2 = 0; i2 < jumps.length; ++i2) {
          if (jumps[i2]) {
            jump_times.push(time_indices[i2] * time_precision);
          }
        }
        timestamps[batch_idx].data.set(jump_times, 1);
      }
      return timestamps;
    }
  }
  class VisionEncoderDecoderModel extends PreTrainedModel {
    /**
     * Creates a new instance of the `VisionEncoderDecoderModel` class.
     * @param {Object} config The configuration object specifying the hyperparameters and other model settings.
     * @param {Object} session The ONNX session containing the encoder model.
     * @param {any} decoder_merged_session The ONNX session containing the merged decoder model.
     * @param {Object} generation_config Configuration object for the generation process.
     */
    constructor(config2, session, decoder_merged_session, generation_config) {
      var _a3;
      super(config2, session);
      __publicField2(this, "main_input_name", "pixel_values");
      this.decoder_merged_session = decoder_merged_session;
      this.generation_config = generation_config;
      const encoderConfig = this.config.encoder;
      const decoderConfig = this.config.decoder;
      const encoderModelType = encoderConfig.model_type;
      const encoderModel = (_a3 = MODEL_MAPPING_NAMES_ENCODER_ONLY.get(encoderModelType)) != null ? _a3 : MODEL_MAPPING_NAMES_ENCODER_DECODER.get(encoderModelType);
      if (!encoderModel) {
        console.warn(`Model type for encoder '${encoderModelType}' not found, assuming encoder-only architecture. Please report this at https://github.com/xenova/transformers.js/issues/new/choose.`);
      }
      const decoderModel = MODEL_WITH_LM_HEAD_MAPPING_NAMES.get(decoderConfig.model_type);
      if (!decoderModel) {
        throw new Error(`Unable to construct \`VisionEncoderDecoder\` due to unsupported decoder: "${this.config.decoder.model_type}"`);
      }
      const decoderModelClass = decoderModel[1];
      const decoder = new decoderModelClass(decoderConfig, decoder_merged_session, generation_config);
      this.add_encoder_pkv = "num_decoder_layers" in decoder;
      if (this.add_encoder_pkv) {
        this.num_decoder_layers = decoder.num_decoder_layers;
        this.num_decoder_heads = decoder.num_decoder_heads;
        this.decoder_dim_kv = decoder.decoder_dim_kv;
        this.num_encoder_layers = decoder.num_encoder_layers;
        this.num_encoder_heads = decoder.num_encoder_heads;
        this.encoder_dim_kv = decoder.encoder_dim_kv;
      } else {
        this.num_layers = decoder.num_layers;
        this.num_heads = decoder.num_heads;
        this.dim_kv = decoder.dim_kv;
      }
    }
  }
  class CLIPPreTrainedModel extends PreTrainedModel {
  }
  class CLIPModel extends CLIPPreTrainedModel {
  }
  class CLIPTextModelWithProjection extends CLIPPreTrainedModel {
    /** @type {PreTrainedModel.from_pretrained} */
    static from_pretrained(_0) {
      return __async(this, arguments, function* (pretrained_model_name_or_path, options = {}) {
        var _a3;
        (_a3 = options.model_file_name) != null ? _a3 : options.model_file_name = "text_model";
        return __superGet(CLIPTextModelWithProjection, this, "from_pretrained").call(this, pretrained_model_name_or_path, options);
      });
    }
  }
  class CLIPVisionModelWithProjection extends CLIPPreTrainedModel {
    /** @type {PreTrainedModel.from_pretrained} */
    static from_pretrained(_0) {
      return __async(this, arguments, function* (pretrained_model_name_or_path, options = {}) {
        var _a3;
        (_a3 = options.model_file_name) != null ? _a3 : options.model_file_name = "vision_model";
        return __superGet(CLIPVisionModelWithProjection, this, "from_pretrained").call(this, pretrained_model_name_or_path, options);
      });
    }
  }
  class SiglipPreTrainedModel extends PreTrainedModel {
  }
  class SiglipModel extends SiglipPreTrainedModel {
  }
  class SiglipTextModel extends SiglipPreTrainedModel {
    /** @type {PreTrainedModel.from_pretrained} */
    static from_pretrained(_0) {
      return __async(this, arguments, function* (pretrained_model_name_or_path, options = {}) {
        var _a3;
        (_a3 = options.model_file_name) != null ? _a3 : options.model_file_name = "text_model";
        return __superGet(SiglipTextModel, this, "from_pretrained").call(this, pretrained_model_name_or_path, options);
      });
    }
  }
  class SiglipVisionModel extends CLIPPreTrainedModel {
    /** @type {PreTrainedModel.from_pretrained} */
    static from_pretrained(_0) {
      return __async(this, arguments, function* (pretrained_model_name_or_path, options = {}) {
        var _a3;
        (_a3 = options.model_file_name) != null ? _a3 : options.model_file_name = "vision_model";
        return __superGet(SiglipVisionModel, this, "from_pretrained").call(this, pretrained_model_name_or_path, options);
      });
    }
  }
  class ChineseCLIPPreTrainedModel extends PreTrainedModel {
  }
  class ChineseCLIPModel extends ChineseCLIPPreTrainedModel {
  }
  class CLIPSegPreTrainedModel extends PreTrainedModel {
  }
  class CLIPSegModel extends CLIPSegPreTrainedModel {
  }
  class CLIPSegForImageSegmentation extends CLIPSegPreTrainedModel {
  }
  class GPT2PreTrainedModel extends PreTrainedModel {
    /**
     * Creates a new instance of the `GPT2PreTrainedModel` class.
     * @param {Object} config The configuration of the model.
     * @param {any} session The ONNX session containing the model weights.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config2, session, generation_config) {
      super(config2, session);
      this.generation_config = generation_config;
      this.config.pad_token_id = this.config.eos_token_id;
      this.num_heads = this.config.n_head;
      this.num_layers = this.config.n_layer;
      this.dim_kv = this.config.n_embd / this.num_heads;
    }
  }
  class GPT2Model extends GPT2PreTrainedModel {
  }
  class GPT2LMHeadModel extends GPT2PreTrainedModel {
  }
  class GPTNeoPreTrainedModel extends PreTrainedModel {
    /**
     * Creates a new instance of the `GPTNeoPreTrainedModel` class.
     * @param {Object} config The configuration of the model.
     * @param {any} session The ONNX session containing the model weights.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config2, session, generation_config) {
      super(config2, session);
      this.generation_config = generation_config;
      this.config.pad_token_id = this.config.eos_token_id;
      this.num_heads = this.config.num_heads;
      this.num_layers = this.config.num_layers;
      this.dim_kv = this.config.hidden_size / this.num_heads;
    }
  }
  class GPTNeoModel extends GPTNeoPreTrainedModel {
  }
  class GPTNeoForCausalLM extends GPTNeoPreTrainedModel {
  }
  class GPTNeoXPreTrainedModel extends PreTrainedModel {
    /**
     * Creates a new instance of the `GPTNeoXPreTrainedModel` class.
     * @param {Object} config The configuration of the model.
     * @param {any} session The ONNX session containing the model weights.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config2, session, generation_config) {
      super(config2, session);
      this.generation_config = generation_config;
      this.config.pad_token_id = this.config.eos_token_id;
      this.num_heads = this.config.num_attention_heads;
      this.num_layers = this.config.num_hidden_layers;
      this.dim_kv = this.config.hidden_size / this.num_heads;
    }
  }
  class GPTNeoXModel extends GPTNeoXPreTrainedModel {
  }
  class GPTNeoXForCausalLM extends GPTNeoXPreTrainedModel {
  }
  class GPTJPreTrainedModel extends PreTrainedModel {
    /**
     * Creates a new instance of the `GPTJPreTrainedModel` class.
     * @param {Object} config The configuration of the model.
     * @param {any} session The ONNX session containing the model weights.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config2, session, generation_config) {
      super(config2, session);
      this.generation_config = generation_config;
      this.config.pad_token_id = this.config.eos_token_id;
      this.num_heads = this.config.n_head;
      this.num_layers = this.config.n_layer;
      this.dim_kv = this.config.n_embd / this.num_heads;
    }
  }
  class GPTJModel extends GPTJPreTrainedModel {
  }
  class GPTJForCausalLM extends GPTJPreTrainedModel {
  }
  class GPTBigCodePreTrainedModel extends PreTrainedModel {
    /**
     * Creates a new instance of the `GPTBigCodePreTrainedModel` class.
     * @param {Object} config The configuration of the model.
     * @param {any} session The ONNX session containing the model weights.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config2, session, generation_config) {
      super(config2, session);
      this.generation_config = generation_config;
      this.config.pad_token_id = this.config.eos_token_id;
      this.num_heads = this.config.n_head;
      this.num_layers = this.config.n_layer;
      this.dim_kv = this.config.n_embd / this.num_heads;
    }
  }
  class GPTBigCodeModel extends GPTBigCodePreTrainedModel {
  }
  class GPTBigCodeForCausalLM extends GPTBigCodePreTrainedModel {
  }
  class CodeGenPreTrainedModel extends PreTrainedModel {
    /**
     * Creates a new instance of the `CodeGenPreTrainedModel` class.
     * @param {Object} config The model configuration object.
     * @param {Object} session The ONNX session object.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config2, session, generation_config) {
      super(config2, session);
      this.generation_config = generation_config;
      this.config.pad_token_id = this.config.eos_token_id;
      this.num_heads = this.config.n_head;
      this.num_layers = this.config.n_layer;
      this.dim_kv = this.config.n_embd / this.num_heads;
    }
  }
  class CodeGenModel extends CodeGenPreTrainedModel {
  }
  class CodeGenForCausalLM extends CodeGenPreTrainedModel {
  }
  class LlamaPreTrainedModel extends PreTrainedModel {
    /**
     * Creates a new instance of the `LlamaPreTrainedModel` class.
     * @param {Object} config The model configuration object.
     * @param {Object} session The ONNX session object.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config2, session, generation_config) {
      var _a3;
      super(config2, session);
      this.generation_config = generation_config;
      this.config.pad_token_id = this.config.eos_token_id;
      this.num_heads = (_a3 = this.config.num_key_value_heads) != null ? _a3 : this.config.num_attention_heads;
      this.num_layers = this.config.num_hidden_layers;
      this.dim_kv = this.config.hidden_size / this.config.num_attention_heads;
    }
  }
  class LlamaModel extends LlamaPreTrainedModel {
  }
  class LlamaForCausalLM extends LlamaPreTrainedModel {
  }
  class Qwen2PreTrainedModel extends PreTrainedModel {
    /**
     * Creates a new instance of the `Qwen2PreTrainedModel` class.
     * @param {Object} config The model configuration object.
     * @param {Object} session The ONNX session object.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config2, session, generation_config) {
      var _a3;
      super(config2, session);
      this.generation_config = generation_config;
      this.config.pad_token_id = this.config.eos_token_id;
      this.num_heads = (_a3 = this.config.num_key_value_heads) != null ? _a3 : this.config.num_attention_heads;
      this.num_layers = this.config.num_hidden_layers;
      this.dim_kv = this.config.hidden_size / this.config.num_attention_heads;
    }
  }
  class Qwen2Model extends Qwen2PreTrainedModel {
  }
  class Qwen2ForCausalLM extends Qwen2PreTrainedModel {
  }
  class PhiPreTrainedModel extends PreTrainedModel {
    /**
     * Creates a new instance of the `PhiPreTrainedModel` class.
     * @param {Object} config The model configuration object.
     * @param {Object} session The ONNX session object.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config2, session, generation_config) {
      super(config2, session);
      this.generation_config = generation_config;
      this.config.pad_token_id = this.config.eos_token_id;
      this.num_heads = this.config.num_attention_heads;
      this.num_layers = this.config.num_hidden_layers;
      this.dim_kv = this.config.hidden_size / this.num_heads;
    }
  }
  class PhiModel extends PhiPreTrainedModel {
  }
  class PhiForCausalLM extends PhiPreTrainedModel {
  }
  class BloomPreTrainedModel extends PreTrainedModel {
    /**
     * Creates a new instance of the `BloomPreTrainedModel` class.
     * @param {Object} config The configuration of the model.
     * @param {any} session The ONNX session containing the model weights.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config2, session, generation_config) {
      super(config2, session);
      this.generation_config = generation_config;
      this.config.pad_token_id = this.config.eos_token_id;
      this.num_heads = this.config.n_head;
      this.num_layers = this.config.n_layer;
      this.dim_kv = this.config.hidden_size / this.num_heads;
    }
  }
  class BloomModel extends BloomPreTrainedModel {
  }
  class BloomForCausalLM extends BloomPreTrainedModel {
  }
  class MptPreTrainedModel extends PreTrainedModel {
    /**
     * Creates a new instance of the `MptPreTrainedModel` class.
     * @param {Object} config The model configuration object.
     * @param {Object} session The ONNX session object.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config2, session, generation_config) {
      super(config2, session);
      this.generation_config = generation_config;
      this.config.pad_token_id = this.config.eos_token_id;
      this.num_heads = this.config.n_heads;
      this.num_layers = this.config.n_layers;
      this.dim_kv = this.config.d_model / this.num_heads;
    }
  }
  class MptModel extends MptPreTrainedModel {
  }
  class MptForCausalLM extends MptPreTrainedModel {
  }
  class OPTPreTrainedModel extends PreTrainedModel {
    /**
     * Creates a new instance of the `OPTPreTrainedModel` class.
     * @param {Object} config The model configuration object.
     * @param {Object} session The ONNX session object.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config2, session, generation_config) {
      super(config2, session);
      this.generation_config = generation_config;
      this.config.pad_token_id = this.config.eos_token_id;
      this.num_heads = this.config.num_attention_heads;
      this.num_layers = this.config.num_hidden_layers;
      this.dim_kv = this.config.hidden_size / this.num_heads;
    }
  }
  class OPTModel extends OPTPreTrainedModel {
  }
  class OPTForCausalLM extends OPTPreTrainedModel {
  }
  class ViTPreTrainedModel extends PreTrainedModel {
  }
  class ViTModel extends ViTPreTrainedModel {
  }
  class ViTForImageClassification extends ViTPreTrainedModel {
    /**
     * @param {any} model_inputs
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new SequenceClassifierOutput(yield __superGet(ViTForImageClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class FastViTPreTrainedModel extends PreTrainedModel {
  }
  class FastViTModel extends FastViTPreTrainedModel {
  }
  class FastViTForImageClassification extends FastViTPreTrainedModel {
    /**
     * @param {any} model_inputs
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new SequenceClassifierOutput(yield __superGet(FastViTForImageClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class VitMattePreTrainedModel extends PreTrainedModel {
  }
  class VitMatteForImageMatting extends VitMattePreTrainedModel {
    /**
     * @param {any} model_inputs
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new ImageMattingOutput(yield __superGet(VitMatteForImageMatting.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class MobileViTPreTrainedModel extends PreTrainedModel {
  }
  class MobileViTModel extends MobileViTPreTrainedModel {
  }
  class MobileViTForImageClassification extends MobileViTPreTrainedModel {
    /**
     * @param {any} model_inputs
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new SequenceClassifierOutput(yield __superGet(MobileViTForImageClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class MobileViTV2PreTrainedModel extends PreTrainedModel {
  }
  class MobileViTV2Model extends MobileViTV2PreTrainedModel {
  }
  class MobileViTV2ForImageClassification extends MobileViTV2PreTrainedModel {
    /**
     * @param {any} model_inputs
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new SequenceClassifierOutput(yield __superGet(MobileViTV2ForImageClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class OwlViTPreTrainedModel extends PreTrainedModel {
  }
  class OwlViTModel extends OwlViTPreTrainedModel {
  }
  class OwlViTForObjectDetection extends OwlViTPreTrainedModel {
  }
  class Owlv2PreTrainedModel extends PreTrainedModel {
  }
  class Owlv2Model extends Owlv2PreTrainedModel {
  }
  class Owlv2ForObjectDetection extends Owlv2PreTrainedModel {
  }
  class BeitPreTrainedModel extends PreTrainedModel {
  }
  class BeitModel extends BeitPreTrainedModel {
  }
  class BeitForImageClassification extends BeitPreTrainedModel {
    /**
     * @param {any} model_inputs
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new SequenceClassifierOutput(yield __superGet(BeitForImageClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class DetrPreTrainedModel extends PreTrainedModel {
  }
  class DetrModel extends DetrPreTrainedModel {
  }
  class DetrForObjectDetection extends DetrPreTrainedModel {
    /**
     * @param {any} model_inputs
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new DetrObjectDetectionOutput(yield __superGet(DetrForObjectDetection.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class DetrForSegmentation extends DetrPreTrainedModel {
    /**
     * Runs the model with the provided inputs
     * @param {Object} model_inputs Model inputs
     * @returns {Promise<DetrSegmentationOutput>} Object containing segmentation outputs
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new DetrSegmentationOutput(yield __superGet(DetrForSegmentation.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class DetrObjectDetectionOutput extends ModelOutput {
    /**
     * @param {Object} output The output of the model.
     * @param {Tensor} output.logits Classification logits (including no-object) for all queries.
     * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height).
     * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding).
     */
    constructor({ logits, pred_boxes }) {
      super();
      this.logits = logits;
      this.pred_boxes = pred_boxes;
    }
  }
  class DetrSegmentationOutput extends ModelOutput {
    /**
     * @param {Object} output The output of the model.
     * @param {Tensor} output.logits The output logits of the model.
     * @param {Tensor} output.pred_boxes Predicted boxes.
     * @param {Tensor} output.pred_masks Predicted masks.
     */
    constructor({ logits, pred_boxes, pred_masks }) {
      super();
      this.logits = logits;
      this.pred_boxes = pred_boxes;
      this.pred_masks = pred_masks;
    }
  }
  class TableTransformerPreTrainedModel extends PreTrainedModel {
  }
  class TableTransformerModel extends TableTransformerPreTrainedModel {
  }
  class TableTransformerForObjectDetection extends TableTransformerPreTrainedModel {
    /**
     * @param {any} model_inputs
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new TableTransformerObjectDetectionOutput(yield __superGet(TableTransformerForObjectDetection.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class TableTransformerObjectDetectionOutput extends DetrObjectDetectionOutput {
  }
  class DeiTPreTrainedModel extends PreTrainedModel {
  }
  class DeiTModel extends DeiTPreTrainedModel {
  }
  class DeiTForImageClassification extends DeiTPreTrainedModel {
    /**
     * @param {any} model_inputs
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new SequenceClassifierOutput(yield __superGet(DeiTForImageClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class ResNetPreTrainedModel extends PreTrainedModel {
  }
  class ResNetModel extends ResNetPreTrainedModel {
  }
  class ResNetForImageClassification extends ResNetPreTrainedModel {
    /**
     * @param {any} model_inputs
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new SequenceClassifierOutput(yield __superGet(ResNetForImageClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class SwinPreTrainedModel extends PreTrainedModel {
  }
  class SwinModel extends SwinPreTrainedModel {
  }
  class SwinForImageClassification extends SwinPreTrainedModel {
    /**
     * @param {any} model_inputs
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new SequenceClassifierOutput(yield __superGet(SwinForImageClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class Swin2SRPreTrainedModel extends PreTrainedModel {
  }
  class Swin2SRModel extends Swin2SRPreTrainedModel {
  }
  class Swin2SRForImageSuperResolution extends Swin2SRPreTrainedModel {
  }
  class DPTPreTrainedModel extends PreTrainedModel {
  }
  class DPTModel extends DPTPreTrainedModel {
  }
  class DPTForDepthEstimation extends DPTPreTrainedModel {
  }
  class DepthAnythingPreTrainedModel extends PreTrainedModel {
  }
  class DepthAnythingForDepthEstimation extends DepthAnythingPreTrainedModel {
  }
  class GLPNPreTrainedModel extends PreTrainedModel {
  }
  class GLPNModel extends GLPNPreTrainedModel {
  }
  class GLPNForDepthEstimation extends GLPNPreTrainedModel {
  }
  class DonutSwinPreTrainedModel extends PreTrainedModel {
  }
  class DonutSwinModel extends DonutSwinPreTrainedModel {
  }
  class ConvNextPreTrainedModel extends PreTrainedModel {
  }
  class ConvNextModel extends ConvNextPreTrainedModel {
  }
  class ConvNextForImageClassification extends ConvNextPreTrainedModel {
    /**
     * @param {any} model_inputs
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new SequenceClassifierOutput(yield __superGet(ConvNextForImageClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class ConvNextV2PreTrainedModel extends PreTrainedModel {
  }
  class ConvNextV2Model extends ConvNextV2PreTrainedModel {
  }
  class ConvNextV2ForImageClassification extends ConvNextV2PreTrainedModel {
    /**
     * @param {any} model_inputs
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new SequenceClassifierOutput(yield __superGet(ConvNextV2ForImageClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class Dinov2PreTrainedModel extends PreTrainedModel {
  }
  class Dinov2Model extends Dinov2PreTrainedModel {
  }
  class Dinov2ForImageClassification extends Dinov2PreTrainedModel {
    /**
     * @param {any} model_inputs
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new SequenceClassifierOutput(yield __superGet(Dinov2ForImageClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class YolosPreTrainedModel extends PreTrainedModel {
  }
  class YolosModel extends YolosPreTrainedModel {
  }
  class YolosForObjectDetection extends YolosPreTrainedModel {
    /**
     * @param {any} model_inputs
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new YolosObjectDetectionOutput(yield __superGet(YolosForObjectDetection.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class YolosObjectDetectionOutput extends ModelOutput {
    /**
     * @param {Object} output The output of the model.
     * @param {Tensor} output.logits Classification logits (including no-object) for all queries.
     * @param {Tensor} output.pred_boxes Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height).
     * These values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding possible padding).
     */
    constructor({ logits, pred_boxes }) {
      super();
      this.logits = logits;
      this.pred_boxes = pred_boxes;
    }
  }
  class SamPreTrainedModel extends PreTrainedModel {
  }
  class SamModel extends SamPreTrainedModel {
    /**
     * Creates a new instance of the `SamModel` class.
     * @param {Object} config The configuration object specifying the hyperparameters and other model settings.
     * @param {Object} vision_encoder The ONNX session containing the vision encoder model.
     * @param {any} prompt_encoder_mask_decoder The ONNX session containing the prompt encoder and mask decoder model.
     */
    constructor(config2, vision_encoder, prompt_encoder_mask_decoder) {
      super(config2, vision_encoder);
      this.prompt_encoder_mask_decoder = prompt_encoder_mask_decoder;
    }
    /**
     * Compute image embeddings and positional image embeddings, given the pixel values of an image.
     * @param {Object} model_inputs Object containing the model inputs.
     * @param {Tensor} model_inputs.pixel_values Pixel values obtained using a `SamProcessor`.
     * @returns {Promise<{ image_embeddings: Tensor, image_positional_embeddings: Tensor }>} The image embeddings and positional image embeddings.
     */
    get_image_embeddings(_0) {
      return __async(this, arguments, function* ({ pixel_values }) {
        return yield encoderForward(this, { pixel_values });
      });
    }
    /**
     * @typedef {Object} SamModelInputs Object containing the model inputs.
     * @property {Tensor} pixel_values Pixel values as a Tensor with shape `(batch_size, num_channels, height, width)`.
     * These can be obtained using a `SamProcessor`.
     * @property {Tensor} input_points Input 2D spatial points with shape `(batch_size, num_points, 2)`.
     * This is used by the prompt encoder to encode the prompt.
     * @property {Tensor} [input_labels] Input labels for the points, as a Tensor of shape `(batch_size, point_batch_size, num_points)`.
     * This is used by the prompt encoder to encode the prompt. There are 4 types of labels:
     *  - `1`: the point is a point that contains the object of interest
     *  - `0`: the point is a point that does not contain the object of interest
     *  - `-1`: the point corresponds to the background
     *  - `-10`: the point is a padding point, thus should be ignored by the prompt encoder
     * @property {Tensor} [image_embeddings] Image embeddings used by the mask decoder.
     * @property {Tensor} [image_positional_embeddings] Image positional embeddings used by the mask decoder.
     */
    /**
     * @param {SamModelInputs} model_inputs Object containing the model inputs.
     * @returns {Promise<Object>} The output of the model.
     */
    forward(model_inputs) {
      return __async(this, null, function* () {
        if (!model_inputs.image_embeddings || !model_inputs.image_positional_embeddings) {
          model_inputs = __spreadValues(__spreadValues({}, model_inputs), yield this.get_image_embeddings(model_inputs));
        }
        if (!model_inputs.input_labels) {
          const shape = model_inputs.input_points.dims.slice(0, -1);
          const numElements = shape.reduce((a, b) => a * b, 1);
          model_inputs.input_labels = new Tensor(
            "int64",
            new BigInt64Array(numElements).fill(/* @__PURE__ */ BigInt("1")),
            shape
          );
        }
        return yield sessionRun(this.prompt_encoder_mask_decoder, {
          input_points: model_inputs.input_points,
          input_labels: model_inputs.input_labels,
          image_embeddings: model_inputs.image_embeddings,
          image_positional_embeddings: model_inputs.image_positional_embeddings
        });
      });
    }
    /**
     * Runs the model with the provided inputs
     * @param {Object} model_inputs Model inputs
     * @returns {Promise<SamImageSegmentationOutput>} Object containing segmentation outputs
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new SamImageSegmentationOutput(yield __superGet(SamModel.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class SamImageSegmentationOutput extends ModelOutput {
    /**
     * @param {Object} output The output of the model.
     * @param {Tensor} output.iou_scores The output logits of the model.
     * @param {Tensor} output.pred_masks Predicted boxes.
     */
    constructor({ iou_scores, pred_masks }) {
      super();
      this.iou_scores = iou_scores;
      this.pred_masks = pred_masks;
    }
  }
  class MarianPreTrainedModel extends PreTrainedModel {
  }
  class MarianModel extends MarianPreTrainedModel {
  }
  class MarianMTModel extends MarianPreTrainedModel {
    /**
     * Creates a new instance of the `MarianMTModel` class.
    * @param {Object} config The model configuration object.
    * @param {Object} session The ONNX session object.
    * @param {any} decoder_merged_session 
    * @param {any} generation_config 
    */
    constructor(config2, session, decoder_merged_session, generation_config) {
      super(config2, session);
      this.decoder_merged_session = decoder_merged_session;
      this.generation_config = generation_config;
      this.num_decoder_layers = this.config.decoder_layers;
      this.num_decoder_heads = this.config.decoder_attention_heads;
      this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads;
      this.num_encoder_layers = this.config.encoder_layers;
      this.num_encoder_heads = this.config.encoder_attention_heads;
      this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads;
    }
  }
  class M2M100PreTrainedModel extends PreTrainedModel {
  }
  class M2M100Model extends M2M100PreTrainedModel {
  }
  class M2M100ForConditionalGeneration extends M2M100PreTrainedModel {
    /**
     * Creates a new instance of the `M2M100ForConditionalGeneration` class.
    * @param {Object} config The model configuration object.
    * @param {Object} session The ONNX session object.
    * @param {any} decoder_merged_session 
    * @param {any} generation_config 
    */
    constructor(config2, session, decoder_merged_session, generation_config) {
      super(config2, session);
      this.decoder_merged_session = decoder_merged_session;
      this.generation_config = generation_config;
      this.num_decoder_layers = this.config.decoder_layers;
      this.num_decoder_heads = this.config.decoder_attention_heads;
      this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads;
      this.num_encoder_layers = this.config.encoder_layers;
      this.num_encoder_heads = this.config.encoder_attention_heads;
      this.encoder_dim_kv = this.config.d_model / this.num_encoder_heads;
    }
  }
  class Wav2Vec2PreTrainedModel extends PreTrainedModel {
  }
  class Wav2Vec2Model extends Wav2Vec2PreTrainedModel {
  }
  class Wav2Vec2ForCTC extends Wav2Vec2PreTrainedModel {
    /**
     * @param {Object} model_inputs
     * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.
     * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new CausalLMOutput(yield __superGet(Wav2Vec2ForCTC.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class Wav2Vec2ForSequenceClassification extends Wav2Vec2PreTrainedModel {
    /**
     * Calls the model on new inputs.
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new SequenceClassifierOutput(yield __superGet(Wav2Vec2ForSequenceClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class Wav2Vec2ForAudioFrameClassification extends Wav2Vec2PreTrainedModel {
    /**
     * Calls the model on new inputs.
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new TokenClassifierOutput(yield __superGet(Wav2Vec2ForAudioFrameClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class UniSpeechPreTrainedModel extends PreTrainedModel {
  }
  class UniSpeechModel extends UniSpeechPreTrainedModel {
  }
  class UniSpeechForCTC extends UniSpeechPreTrainedModel {
    /**
     * @param {Object} model_inputs
     * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.
     * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new CausalLMOutput(yield __superGet(UniSpeechForCTC.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class UniSpeechForSequenceClassification extends UniSpeechPreTrainedModel {
    /**
     * Calls the model on new inputs.
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new SequenceClassifierOutput(yield __superGet(UniSpeechForSequenceClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class UniSpeechSatPreTrainedModel extends PreTrainedModel {
  }
  class UniSpeechSatModel extends UniSpeechSatPreTrainedModel {
  }
  class UniSpeechSatForCTC extends UniSpeechSatPreTrainedModel {
    /**
     * @param {Object} model_inputs
     * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.
     * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new CausalLMOutput(yield __superGet(UniSpeechSatForCTC.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class UniSpeechSatForSequenceClassification extends UniSpeechSatPreTrainedModel {
    /**
     * Calls the model on new inputs.
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new SequenceClassifierOutput(yield __superGet(UniSpeechSatForSequenceClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class UniSpeechSatForAudioFrameClassification extends UniSpeechSatPreTrainedModel {
    /**
     * Calls the model on new inputs.
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new TokenClassifierOutput(yield __superGet(UniSpeechSatForAudioFrameClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class Wav2Vec2BertPreTrainedModel extends PreTrainedModel {
  }
  class Wav2Vec2BertModel extends Wav2Vec2BertPreTrainedModel {
  }
  class Wav2Vec2BertForCTC extends Wav2Vec2BertPreTrainedModel {
    /**
     * @param {Object} model_inputs
     * @param {Tensor} model_inputs.input_features Float values of input mel-spectrogram.
     * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new CausalLMOutput(yield __superGet(Wav2Vec2BertForCTC.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class Wav2Vec2BertForSequenceClassification extends Wav2Vec2BertPreTrainedModel {
    /**
     * Calls the model on new inputs.
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new SequenceClassifierOutput(yield __superGet(Wav2Vec2BertForSequenceClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class HubertModel extends Wav2Vec2PreTrainedModel {
  }
  class HubertForCTC extends Wav2Vec2PreTrainedModel {
    /**
     * @param {Object} model_inputs
     * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.
     * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new CausalLMOutput(yield __superGet(HubertForCTC.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class HubertForSequenceClassification extends Wav2Vec2PreTrainedModel {
    /**
     * Calls the model on new inputs.
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new SequenceClassifierOutput(yield __superGet(HubertForSequenceClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class WavLMPreTrainedModel extends PreTrainedModel {
  }
  class WavLMModel extends WavLMPreTrainedModel {
  }
  class WavLMForCTC extends WavLMPreTrainedModel {
    /**
     * @param {Object} model_inputs
     * @param {Tensor} model_inputs.input_values Float values of input raw speech waveform.
     * @param {Tensor} model_inputs.attention_mask Mask to avoid performing convolution and attention on padding token indices. Mask values selected in [0, 1]
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new CausalLMOutput(yield __superGet(WavLMForCTC.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class WavLMForSequenceClassification extends WavLMPreTrainedModel {
    /**
     * Calls the model on new inputs.
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<SequenceClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new SequenceClassifierOutput(yield __superGet(WavLMForSequenceClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class WavLMForXVector extends WavLMPreTrainedModel {
    /**
     * Calls the model on new inputs.
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<XVectorOutput>} An object containing the model's output logits and speaker embeddings.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new XVectorOutput(yield __superGet(WavLMForXVector.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class WavLMForAudioFrameClassification extends WavLMPreTrainedModel {
    /**
     * Calls the model on new inputs.
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<TokenClassifierOutput>} An object containing the model's output logits for sequence classification.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new TokenClassifierOutput(yield __superGet(WavLMForAudioFrameClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class SpeechT5PreTrainedModel extends PreTrainedModel {
  }
  class SpeechT5ForSpeechToText extends SpeechT5PreTrainedModel {
  }
  class SpeechT5ForTextToSpeech extends SpeechT5PreTrainedModel {
    /**
     * Creates a new instance of the `SpeechT5ForTextToSpeech` class.
     * @param {Object} config The model configuration.
     * @param {any} session session for the model.
     * @param {any} decoder_merged_session session for the decoder.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config2, session, decoder_merged_session, generation_config) {
      super(config2, session);
      this.decoder_merged_session = decoder_merged_session;
      this.generation_config = generation_config;
      this.num_decoder_layers = this.config.decoder_layers;
      this.num_decoder_heads = this.config.decoder_attention_heads;
      this.decoder_dim_kv = this.config.hidden_size / this.num_decoder_heads;
      this.num_encoder_layers = this.config.encoder_layers;
      this.num_encoder_heads = this.config.encoder_attention_heads;
      this.encoder_dim_kv = this.config.hidden_size / this.num_encoder_heads;
    }
    /**
     * @typedef {Object} SpeechOutput
     * @property {Tensor} [spectrogram] The predicted log-mel spectrogram of shape
     * `(output_sequence_length, config.num_mel_bins)`. Returned when no `vocoder` is provided
     * @property {Tensor} [waveform] The predicted waveform of shape `(num_frames,)`. Returned when a `vocoder` is provided.
     * @property {Tensor} [cross_attentions] The outputs of the decoder's cross-attention layers of shape
     * `(config.decoder_layers, config.decoder_attention_heads, output_sequence_length, input_sequence_length)`. returned when `output_cross_attentions` is `true`.
     */
    /**
     * Converts a sequence of input tokens into a sequence of mel spectrograms, which are subsequently turned into a speech waveform using a vocoder.
     * @param {Tensor} input_values Indices of input sequence tokens in the vocabulary.
     * @param {Tensor} speaker_embeddings Tensor containing the speaker embeddings.
     * @param {Object} options Optional parameters for generating speech.
     * @param {number} [options.threshold=0.5] The generated sequence ends when the predicted stop token probability exceeds this value.
     * @param {number} [options.minlenratio=0.0] Used to calculate the minimum required length for the output sequence.
     * @param {number} [options.maxlenratio=20.0] Used to calculate the maximum allowed length for the output sequence.
     * @param {Object} [options.vocoder=null] The vocoder that converts the mel spectrogram into a speech waveform. If `null`, the output is the mel spectrogram.
     * @param {boolean} [options.output_cross_attentions=false] Whether or not to return the attentions tensors of the decoder's cross-attention layers.
     * @returns {Promise<SpeechOutput>} A promise which resolves to an object containing the spectrogram, waveform, and cross-attention tensors.
     */
    generate_speech(_0, _1) {
      return __async(this, arguments, function* (input_values, speaker_embeddings, {
        threshold = 0.5,
        minlenratio = 0,
        maxlenratio = 20,
        vocoder = null
        // output_cross_attentions = false, // TODO add
      } = {}) {
        const model_inputs = {
          input_ids: input_values
        };
        const { encoder_outputs, encoder_attention_mask } = yield encoderForward(this, model_inputs);
        const r = encoder_outputs.dims[1] / this.config.reduction_factor;
        const maxlen = Math.floor(r * maxlenratio);
        const minlen = Math.floor(r * minlenratio);
        const num_mel_bins = this.config.num_mel_bins;
        let spectrogramParts = [];
        let past_key_values = null;
        let decoder_outputs = null;
        let idx = 0;
        while (true) {
          ++idx;
          const use_cache_branch = boolTensor(!!decoder_outputs);
          let output_sequence;
          if (decoder_outputs) {
            output_sequence = decoder_outputs.output_sequence_out;
          } else {
            output_sequence = new Tensor(
              "float32",
              new Float32Array(num_mel_bins),
              [1, 1, num_mel_bins]
            );
          }
          let decoderFeeds = {
            use_cache_branch,
            output_sequence,
            encoder_attention_mask,
            speaker_embeddings,
            encoder_hidden_states: encoder_outputs
          };
          this.addPastKeyValues(decoderFeeds, past_key_values);
          decoder_outputs = yield sessionRun(this.decoder_merged_session, decoderFeeds);
          past_key_values = this.getPastKeyValues(decoder_outputs, past_key_values);
          const { prob, spectrum } = decoder_outputs;
          spectrogramParts.push(spectrum);
          if (idx >= minlen && // Finished when stop token or maximum length is reached.
          (Array.from(prob.data).filter((p) => p >= threshold).length > 0 || idx >= maxlen)) {
            break;
          }
        }
        const spectrogram = cat(spectrogramParts);
        const { waveform } = yield sessionRun(vocoder.session, { spectrogram });
        return {
          spectrogram,
          waveform
          // cross_attentions: null, // TODO add
        };
      });
    }
  }
  class SpeechT5HifiGan extends PreTrainedModel {
    constructor() {
      super(...arguments);
      __publicField2(this, "main_input_name", "spectrogram");
    }
  }
  class TrOCRPreTrainedModel extends PreTrainedModel {
    /**
     * Creates a new instance of the `TrOCRPreTrainedModel` class.
     * @param {Object} config The configuration of the model.
     * @param {any} session The ONNX session containing the model weights.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config2, session, generation_config) {
      super(config2, session);
      this.generation_config = generation_config;
      this.config.pad_token_id = this.config.eos_token_id;
      this.num_encoder_layers = this.num_decoder_layers = this.config.decoder_layers;
      this.num_encoder_heads = this.num_decoder_heads = this.config.decoder_attention_heads;
      this.encoder_dim_kv = this.decoder_dim_kv = this.config.d_model / this.num_decoder_heads;
    }
  }
  class TrOCRForCausalLM extends TrOCRPreTrainedModel {
  }
  class MistralPreTrainedModel extends PreTrainedModel {
    /**
     * Creates a new instance of the `MistralPreTrainedModel` class.
     * @param {Object} config The configuration of the model.
     * @param {any} session The ONNX session containing the model weights.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config2, session, generation_config) {
      super(config2, session);
      this.generation_config = generation_config;
      this.config.pad_token_id = this.config.eos_token_id;
      this.num_heads = this.config.num_key_value_heads;
      this.num_layers = this.config.num_hidden_layers;
      this.dim_kv = this.config.hidden_size / this.config.num_attention_heads;
    }
  }
  class MistralModel extends MistralPreTrainedModel {
  }
  class MistralForCausalLM extends MistralPreTrainedModel {
  }
  class Starcoder2PreTrainedModel extends PreTrainedModel {
    /**
     * Creates a new instance of the `Starcoder2PreTrainedModel` class.
     * @param {Object} config The configuration of the model.
     * @param {any} session The ONNX session containing the model weights.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config2, session, generation_config) {
      super(config2, session);
      this.generation_config = generation_config;
      this.config.pad_token_id = this.config.eos_token_id;
      this.num_heads = this.config.num_key_value_heads;
      this.num_layers = this.config.num_hidden_layers;
      this.dim_kv = this.config.hidden_size / this.config.num_attention_heads;
    }
  }
  class Starcoder2Model extends Starcoder2PreTrainedModel {
  }
  class Starcoder2ForCausalLM extends Starcoder2PreTrainedModel {
  }
  class FalconPreTrainedModel extends PreTrainedModel {
    /**
     * Creates a new instance of the `FalconPreTrainedModel` class.
     * @param {Object} config The configuration of the model.
     * @param {any} session The ONNX session containing the model weights.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config2, session, generation_config) {
      super(config2, session);
      this.generation_config = generation_config;
      this.config.pad_token_id = this.config.eos_token_id;
      this.num_heads = this.config.num_attention_heads;
      this.num_layers = this.config.num_hidden_layers;
      this.dim_kv = this.config.hidden_size / this.config.num_attention_heads;
    }
  }
  class FalconModel extends FalconPreTrainedModel {
  }
  class FalconForCausalLM extends FalconPreTrainedModel {
  }
  class ClapPreTrainedModel extends PreTrainedModel {
  }
  class ClapModel extends ClapPreTrainedModel {
  }
  class ClapTextModelWithProjection extends ClapPreTrainedModel {
    /** @type {PreTrainedModel.from_pretrained} */
    static from_pretrained(_0) {
      return __async(this, arguments, function* (pretrained_model_name_or_path, options = {}) {
        var _a3;
        (_a3 = options.model_file_name) != null ? _a3 : options.model_file_name = "text_model";
        return __superGet(ClapTextModelWithProjection, this, "from_pretrained").call(this, pretrained_model_name_or_path, options);
      });
    }
  }
  class ClapAudioModelWithProjection extends ClapPreTrainedModel {
    /** @type {PreTrainedModel.from_pretrained} */
    static from_pretrained(_0) {
      return __async(this, arguments, function* (pretrained_model_name_or_path, options = {}) {
        var _a3;
        (_a3 = options.model_file_name) != null ? _a3 : options.model_file_name = "audio_model";
        return __superGet(ClapAudioModelWithProjection, this, "from_pretrained").call(this, pretrained_model_name_or_path, options);
      });
    }
  }
  class VitsPreTrainedModel extends PreTrainedModel {
  }
  class VitsModel extends VitsPreTrainedModel {
    /**
     * Calls the model on new inputs.
     * @param {Object} model_inputs The inputs to the model.
     * @returns {Promise<VitsModelOutput>} The outputs for the VITS model.
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new VitsModelOutput(yield __superGet(VitsModel.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class SegformerPreTrainedModel extends PreTrainedModel {
  }
  class SegformerForImageClassification extends SegformerPreTrainedModel {
  }
  class SegformerForSemanticSegmentation extends SegformerPreTrainedModel {
  }
  class StableLmPreTrainedModel extends PreTrainedModel {
    /**
     * Creates a new instance of the `StableLmPreTrainedModel` class.
     * @param {Object} config The configuration of the model.
     * @param {any} session The ONNX session containing the model weights.
     * @param {GenerationConfig} generation_config The generation configuration.
     */
    constructor(config2, session, generation_config) {
      super(config2, session);
      this.generation_config = generation_config;
      this.config.pad_token_id = this.config.eos_token_id;
      this.num_heads = this.config.num_attention_heads;
      this.num_layers = this.config.num_hidden_layers;
      this.dim_kv = this.config.hidden_size / this.num_heads;
    }
  }
  class StableLmForCausalLM extends StableLmPreTrainedModel {
  }
  class EfficientNetPreTrainedModel extends PreTrainedModel {
  }
  class EfficientNetModel extends EfficientNetPreTrainedModel {
  }
  class EfficientNetForImageClassification extends EfficientNetPreTrainedModel {
    /**
     * @param {any} model_inputs
     */
    _call(model_inputs) {
      return __async(this, null, function* () {
        return new SequenceClassifierOutput(yield __superGet(EfficientNetForImageClassification.prototype, this, "_call").call(this, model_inputs));
      });
    }
  }
  class PretrainedMixin {
    /** @type {PreTrainedModel.from_pretrained} */
    static from_pretrained(_0) {
      return __async(this, arguments, function* (pretrained_model_name_or_path, {
        quantized = true,
        progress_callback = null,
        config: config2 = null,
        cache_dir = null,
        local_files_only = false,
        revision = "main",
        model_file_name = null
      } = {}) {
        let options = {
          quantized,
          progress_callback,
          config: config2,
          cache_dir,
          local_files_only,
          revision,
          model_file_name
        };
        config2 = yield AutoConfig.from_pretrained(pretrained_model_name_or_path, options);
        if (!options.config) {
          options.config = config2;
        }
        if (!this.MODEL_CLASS_MAPPINGS) {
          throw new Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: " + this.name);
        }
        for (let MODEL_CLASS_MAPPING of this.MODEL_CLASS_MAPPINGS) {
          const modelInfo = MODEL_CLASS_MAPPING.get(config2.model_type);
          if (!modelInfo) {
            continue;
          }
          return yield modelInfo[1].from_pretrained(pretrained_model_name_or_path, options);
        }
        if (this.BASE_IF_FAIL) {
          console.warn(`Unknown model class "${config2.model_type}", attempting to construct from base class.`);
          return yield PreTrainedModel.from_pretrained(pretrained_model_name_or_path, options);
        } else {
          throw Error(`Unsupported model type: ${config2.model_type}`);
        }
      });
    }
  }
  /**
   * Mapping from model type to model class.
   * @type {Map<string, Object>[]}
   */
  __publicField2(PretrainedMixin, "MODEL_CLASS_MAPPINGS", null);
  /**
   * Whether to attempt to instantiate the base class (`PretrainedModel`) if 
   * the model type is not found in the mapping.
   */
  __publicField2(PretrainedMixin, "BASE_IF_FAIL", false);
  const MODEL_MAPPING_NAMES_ENCODER_ONLY = /* @__PURE__ */ new Map([
    ["bert", ["BertModel", BertModel]],
    ["nomic_bert", ["NomicBertModel", NomicBertModel]],
    ["roformer", ["RoFormerModel", RoFormerModel]],
    ["electra", ["ElectraModel", ElectraModel]],
    ["esm", ["EsmModel", EsmModel]],
    ["convbert", ["ConvBertModel", ConvBertModel]],
    ["camembert", ["CamembertModel", CamembertModel]],
    ["deberta", ["DebertaModel", DebertaModel]],
    ["deberta-v2", ["DebertaV2Model", DebertaV2Model]],
    ["mpnet", ["MPNetModel", MPNetModel]],
    ["albert", ["AlbertModel", AlbertModel]],
    ["distilbert", ["DistilBertModel", DistilBertModel]],
    ["roberta", ["RobertaModel", RobertaModel]],
    ["xlm", ["XLMModel", XLMModel]],
    ["xlm-roberta", ["XLMRobertaModel", XLMRobertaModel]],
    ["clap", ["ClapModel", ClapModel]],
    ["clip", ["CLIPModel", CLIPModel]],
    ["clipseg", ["CLIPSegModel", CLIPSegModel]],
    ["chinese_clip", ["ChineseCLIPModel", ChineseCLIPModel]],
    ["siglip", ["SiglipModel", SiglipModel]],
    ["mobilebert", ["MobileBertModel", MobileBertModel]],
    ["squeezebert", ["SqueezeBertModel", SqueezeBertModel]],
    ["wav2vec2", ["Wav2Vec2Model", Wav2Vec2Model]],
    ["wav2vec2-bert", ["Wav2Vec2BertModel", Wav2Vec2BertModel]],
    ["unispeech", ["UniSpeechModel", UniSpeechModel]],
    ["unispeech-sat", ["UniSpeechSatModel", UniSpeechSatModel]],
    ["hubert", ["HubertModel", HubertModel]],
    ["wavlm", ["WavLMModel", WavLMModel]],
    ["audio-spectrogram-transformer", ["ASTModel", ASTModel]],
    ["vits", ["VitsModel", VitsModel]],
    ["detr", ["DetrModel", DetrModel]],
    ["table-transformer", ["TableTransformerModel", TableTransformerModel]],
    ["vit", ["ViTModel", ViTModel]],
    ["fastvit", ["FastViTModel", FastViTModel]],
    ["mobilevit", ["MobileViTModel", MobileViTModel]],
    ["mobilevitv2", ["MobileViTV2Model", MobileViTV2Model]],
    ["owlvit", ["OwlViTModel", OwlViTModel]],
    ["owlv2", ["Owlv2Model", Owlv2Model]],
    ["beit", ["BeitModel", BeitModel]],
    ["deit", ["DeiTModel", DeiTModel]],
    ["convnext", ["ConvNextModel", ConvNextModel]],
    ["convnextv2", ["ConvNextV2Model", ConvNextV2Model]],
    ["dinov2", ["Dinov2Model", Dinov2Model]],
    ["resnet", ["ResNetModel", ResNetModel]],
    ["swin", ["SwinModel", SwinModel]],
    ["swin2sr", ["Swin2SRModel", Swin2SRModel]],
    ["donut-swin", ["DonutSwinModel", DonutSwinModel]],
    ["yolos", ["YolosModel", YolosModel]],
    ["dpt", ["DPTModel", DPTModel]],
    ["glpn", ["GLPNModel", GLPNModel]],
    ["hifigan", ["SpeechT5HifiGan", SpeechT5HifiGan]],
    ["efficientnet", ["EfficientNetModel", EfficientNetModel]]
  ]);
  const MODEL_MAPPING_NAMES_ENCODER_DECODER = /* @__PURE__ */ new Map([
    ["t5", ["T5Model", T5Model]],
    ["longt5", ["LongT5Model", LongT5Model]],
    ["mt5", ["MT5Model", MT5Model]],
    ["bart", ["BartModel", BartModel]],
    ["mbart", ["MBartModel", MBartModel]],
    ["marian", ["MarianModel", MarianModel]],
    ["whisper", ["WhisperModel", WhisperModel]],
    ["m2m_100", ["M2M100Model", M2M100Model]],
    ["blenderbot", ["BlenderbotModel", BlenderbotModel]],
    ["blenderbot-small", ["BlenderbotSmallModel", BlenderbotSmallModel]]
  ]);
  const MODEL_MAPPING_NAMES_DECODER_ONLY = /* @__PURE__ */ new Map([
    ["bloom", ["BloomModel", BloomModel]],
    ["gpt2", ["GPT2Model", GPT2Model]],
    ["gptj", ["GPTJModel", GPTJModel]],
    ["gpt_bigcode", ["GPTBigCodeModel", GPTBigCodeModel]],
    ["gpt_neo", ["GPTNeoModel", GPTNeoModel]],
    ["gpt_neox", ["GPTNeoXModel", GPTNeoXModel]],
    ["codegen", ["CodeGenModel", CodeGenModel]],
    ["llama", ["LlamaModel", LlamaModel]],
    ["qwen2", ["Qwen2Model", Qwen2Model]],
    ["phi", ["PhiModel", PhiModel]],
    ["mpt", ["MptModel", MptModel]],
    ["opt", ["OPTModel", OPTModel]],
    ["mistral", ["MistralModel", MistralModel]],
    ["starcoder2", ["Starcoder2Model", Starcoder2Model]],
    ["falcon", ["FalconModel", FalconModel]]
  ]);
  const MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES = /* @__PURE__ */ new Map([
    ["speecht5", ["SpeechT5ForSpeechToText", SpeechT5ForSpeechToText]],
    ["whisper", ["WhisperForConditionalGeneration", WhisperForConditionalGeneration]]
  ]);
  const MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES = /* @__PURE__ */ new Map([
    ["speecht5", ["SpeechT5ForTextToSpeech", SpeechT5ForTextToSpeech]]
  ]);
  const MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES = /* @__PURE__ */ new Map([
    ["vits", ["VitsModel", VitsModel]]
  ]);
  const MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES = /* @__PURE__ */ new Map([
    ["bert", ["BertForSequenceClassification", BertForSequenceClassification]],
    ["roformer", ["RoFormerForSequenceClassification", RoFormerForSequenceClassification]],
    ["electra", ["ElectraForSequenceClassification", ElectraForSequenceClassification]],
    ["esm", ["EsmForSequenceClassification", EsmForSequenceClassification]],
    ["convbert", ["ConvBertForSequenceClassification", ConvBertForSequenceClassification]],
    ["camembert", ["CamembertForSequenceClassification", CamembertForSequenceClassification]],
    ["deberta", ["DebertaForSequenceClassification", DebertaForSequenceClassification]],
    ["deberta-v2", ["DebertaV2ForSequenceClassification", DebertaV2ForSequenceClassification]],
    ["mpnet", ["MPNetForSequenceClassification", MPNetForSequenceClassification]],
    ["albert", ["AlbertForSequenceClassification", AlbertForSequenceClassification]],
    ["distilbert", ["DistilBertForSequenceClassification", DistilBertForSequenceClassification]],
    ["roberta", ["RobertaForSequenceClassification", RobertaForSequenceClassification]],
    ["xlm", ["XLMForSequenceClassification", XLMForSequenceClassification]],
    ["xlm-roberta", ["XLMRobertaForSequenceClassification", XLMRobertaForSequenceClassification]],
    ["bart", ["BartForSequenceClassification", BartForSequenceClassification]],
    ["mbart", ["MBartForSequenceClassification", MBartForSequenceClassification]],
    ["mobilebert", ["MobileBertForSequenceClassification", MobileBertForSequenceClassification]],
    ["squeezebert", ["SqueezeBertForSequenceClassification", SqueezeBertForSequenceClassification]]
  ]);
  const MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES = /* @__PURE__ */ new Map([
    ["bert", ["BertForTokenClassification", BertForTokenClassification]],
    ["roformer", ["RoFormerForTokenClassification", RoFormerForTokenClassification]],
    ["electra", ["ElectraForTokenClassification", ElectraForTokenClassification]],
    ["esm", ["EsmForTokenClassification", EsmForTokenClassification]],
    ["convbert", ["ConvBertForTokenClassification", ConvBertForTokenClassification]],
    ["camembert", ["CamembertForTokenClassification", CamembertForTokenClassification]],
    ["deberta", ["DebertaForTokenClassification", DebertaForTokenClassification]],
    ["deberta-v2", ["DebertaV2ForTokenClassification", DebertaV2ForTokenClassification]],
    ["mpnet", ["MPNetForTokenClassification", MPNetForTokenClassification]],
    ["distilbert", ["DistilBertForTokenClassification", DistilBertForTokenClassification]],
    ["roberta", ["RobertaForTokenClassification", RobertaForTokenClassification]],
    ["xlm", ["XLMForTokenClassification", XLMForTokenClassification]],
    ["xlm-roberta", ["XLMRobertaForTokenClassification", XLMRobertaForTokenClassification]]
  ]);
  const MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES = /* @__PURE__ */ new Map([
    ["t5", ["T5ForConditionalGeneration", T5ForConditionalGeneration]],
    ["longt5", ["LongT5ForConditionalGeneration", LongT5ForConditionalGeneration]],
    ["mt5", ["MT5ForConditionalGeneration", MT5ForConditionalGeneration]],
    ["bart", ["BartForConditionalGeneration", BartForConditionalGeneration]],
    ["mbart", ["MBartForConditionalGeneration", MBartForConditionalGeneration]],
    ["marian", ["MarianMTModel", MarianMTModel]],
    ["m2m_100", ["M2M100ForConditionalGeneration", M2M100ForConditionalGeneration]],
    ["blenderbot", ["BlenderbotForConditionalGeneration", BlenderbotForConditionalGeneration]],
    ["blenderbot-small", ["BlenderbotSmallForConditionalGeneration", BlenderbotSmallForConditionalGeneration]]
  ]);
  const MODEL_WITH_LM_HEAD_MAPPING_NAMES = /* @__PURE__ */ new Map([
    ["bloom", ["BloomForCausalLM", BloomForCausalLM]],
    ["gpt2", ["GPT2LMHeadModel", GPT2LMHeadModel]],
    ["gptj", ["GPTJForCausalLM", GPTJForCausalLM]],
    ["gpt_bigcode", ["GPTBigCodeForCausalLM", GPTBigCodeForCausalLM]],
    ["gpt_neo", ["GPTNeoForCausalLM", GPTNeoForCausalLM]],
    ["gpt_neox", ["GPTNeoXForCausalLM", GPTNeoXForCausalLM]],
    ["codegen", ["CodeGenForCausalLM", CodeGenForCausalLM]],
    ["llama", ["LlamaForCausalLM", LlamaForCausalLM]],
    ["qwen2", ["Qwen2ForCausalLM", Qwen2ForCausalLM]],
    ["phi", ["PhiForCausalLM", PhiForCausalLM]],
    ["mpt", ["MptForCausalLM", MptForCausalLM]],
    ["opt", ["OPTForCausalLM", OPTForCausalLM]],
    ["mbart", ["MBartForCausalLM", MBartForCausalLM]],
    ["mistral", ["MistralForCausalLM", MistralForCausalLM]],
    ["starcoder2", ["Starcoder2ForCausalLM", Starcoder2ForCausalLM]],
    ["falcon", ["FalconForCausalLM", FalconForCausalLM]],
    ["trocr", ["TrOCRForCausalLM", TrOCRForCausalLM]],
    ["stablelm", ["StableLmForCausalLM", StableLmForCausalLM]]
  ]);
  const MODEL_FOR_MASKED_LM_MAPPING_NAMES = /* @__PURE__ */ new Map([
    ["bert", ["BertForMaskedLM", BertForMaskedLM]],
    ["roformer", ["RoFormerForMaskedLM", RoFormerForMaskedLM]],
    ["electra", ["ElectraForMaskedLM", ElectraForMaskedLM]],
    ["esm", ["EsmForMaskedLM", EsmForMaskedLM]],
    ["convbert", ["ConvBertForMaskedLM", ConvBertForMaskedLM]],
    ["camembert", ["CamembertForMaskedLM", CamembertForMaskedLM]],
    ["deberta", ["DebertaForMaskedLM", DebertaForMaskedLM]],
    ["deberta-v2", ["DebertaV2ForMaskedLM", DebertaV2ForMaskedLM]],
    ["mpnet", ["MPNetForMaskedLM", MPNetForMaskedLM]],
    ["albert", ["AlbertForMaskedLM", AlbertForMaskedLM]],
    ["distilbert", ["DistilBertForMaskedLM", DistilBertForMaskedLM]],
    ["roberta", ["RobertaForMaskedLM", RobertaForMaskedLM]],
    ["xlm", ["XLMWithLMHeadModel", XLMWithLMHeadModel]],
    ["xlm-roberta", ["XLMRobertaForMaskedLM", XLMRobertaForMaskedLM]],
    ["mobilebert", ["MobileBertForMaskedLM", MobileBertForMaskedLM]],
    ["squeezebert", ["SqueezeBertForMaskedLM", SqueezeBertForMaskedLM]]
  ]);
  const MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES = /* @__PURE__ */ new Map([
    ["bert", ["BertForQuestionAnswering", BertForQuestionAnswering]],
    ["roformer", ["RoFormerForQuestionAnswering", RoFormerForQuestionAnswering]],
    ["electra", ["ElectraForQuestionAnswering", ElectraForQuestionAnswering]],
    ["convbert", ["ConvBertForQuestionAnswering", ConvBertForQuestionAnswering]],
    ["camembert", ["CamembertForQuestionAnswering", CamembertForQuestionAnswering]],
    ["deberta", ["DebertaForQuestionAnswering", DebertaForQuestionAnswering]],
    ["deberta-v2", ["DebertaV2ForQuestionAnswering", DebertaV2ForQuestionAnswering]],
    ["mpnet", ["MPNetForQuestionAnswering", MPNetForQuestionAnswering]],
    ["albert", ["AlbertForQuestionAnswering", AlbertForQuestionAnswering]],
    ["distilbert", ["DistilBertForQuestionAnswering", DistilBertForQuestionAnswering]],
    ["roberta", ["RobertaForQuestionAnswering", RobertaForQuestionAnswering]],
    ["xlm", ["XLMForQuestionAnswering", XLMForQuestionAnswering]],
    ["xlm-roberta", ["XLMRobertaForQuestionAnswering", XLMRobertaForQuestionAnswering]],
    ["mobilebert", ["MobileBertForQuestionAnswering", MobileBertForQuestionAnswering]],
    ["squeezebert", ["SqueezeBertForQuestionAnswering", SqueezeBertForQuestionAnswering]]
  ]);
  const MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES = /* @__PURE__ */ new Map([
    ["vision-encoder-decoder", ["VisionEncoderDecoderModel", VisionEncoderDecoderModel]]
  ]);
  const MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES = /* @__PURE__ */ new Map([
    ["vit", ["ViTForImageClassification", ViTForImageClassification]],
    ["fastvit", ["FastViTForImageClassification", FastViTForImageClassification]],
    ["mobilevit", ["MobileViTForImageClassification", MobileViTForImageClassification]],
    ["mobilevitv2", ["MobileViTV2ForImageClassification", MobileViTV2ForImageClassification]],
    ["beit", ["BeitForImageClassification", BeitForImageClassification]],
    ["deit", ["DeiTForImageClassification", DeiTForImageClassification]],
    ["convnext", ["ConvNextForImageClassification", ConvNextForImageClassification]],
    ["convnextv2", ["ConvNextV2ForImageClassification", ConvNextV2ForImageClassification]],
    ["dinov2", ["Dinov2ForImageClassification", Dinov2ForImageClassification]],
    ["resnet", ["ResNetForImageClassification", ResNetForImageClassification]],
    ["swin", ["SwinForImageClassification", SwinForImageClassification]],
    ["segformer", ["SegformerForImageClassification", SegformerForImageClassification]],
    ["efficientnet", ["EfficientNetForImageClassification", EfficientNetForImageClassification]]
  ]);
  const MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES = /* @__PURE__ */ new Map([
    ["detr", ["DetrForObjectDetection", DetrForObjectDetection]],
    ["table-transformer", ["TableTransformerForObjectDetection", TableTransformerForObjectDetection]],
    ["yolos", ["YolosForObjectDetection", YolosForObjectDetection]]
  ]);
  const MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES = /* @__PURE__ */ new Map([
    ["owlvit", ["OwlViTForObjectDetection", OwlViTForObjectDetection]],
    ["owlv2", ["Owlv2ForObjectDetection", Owlv2ForObjectDetection]]
  ]);
  const MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES = /* @__PURE__ */ new Map([
    ["detr", ["DetrForSegmentation", DetrForSegmentation]],
    ["clipseg", ["CLIPSegForImageSegmentation", CLIPSegForImageSegmentation]]
  ]);
  const MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES = /* @__PURE__ */ new Map([
    ["segformer", ["SegformerForSemanticSegmentation", SegformerForSemanticSegmentation]]
  ]);
  const MODEL_FOR_MASK_GENERATION_MAPPING_NAMES = /* @__PURE__ */ new Map([
    ["sam", ["SamModel", SamModel]]
  ]);
  const MODEL_FOR_CTC_MAPPING_NAMES = /* @__PURE__ */ new Map([
    ["wav2vec2", ["Wav2Vec2ForCTC", Wav2Vec2ForCTC]],
    ["wav2vec2-bert", ["Wav2Vec2BertForCTC", Wav2Vec2BertForCTC]],
    ["unispeech", ["UniSpeechForCTC", UniSpeechForCTC]],
    ["unispeech-sat", ["UniSpeechSatForCTC", UniSpeechSatForCTC]],
    ["wavlm", ["WavLMForCTC", WavLMForCTC]],
    ["hubert", ["HubertForCTC", HubertForCTC]]
  ]);
  const MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES = /* @__PURE__ */ new Map([
    ["wav2vec2", ["Wav2Vec2ForSequenceClassification", Wav2Vec2ForSequenceClassification]],
    ["wav2vec2-bert", ["Wav2Vec2BertForSequenceClassification", Wav2Vec2BertForSequenceClassification]],
    ["unispeech", ["UniSpeechForSequenceClassification", UniSpeechForSequenceClassification]],
    ["unispeech-sat", ["UniSpeechSatForSequenceClassification", UniSpeechSatForSequenceClassification]],
    ["wavlm", ["WavLMForSequenceClassification", WavLMForSequenceClassification]],
    ["hubert", ["HubertForSequenceClassification", HubertForSequenceClassification]],
    ["audio-spectrogram-transformer", ["ASTForAudioClassification", ASTForAudioClassification]]
  ]);
  const MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES = /* @__PURE__ */ new Map([
    ["wavlm", ["WavLMForXVector", WavLMForXVector]]
  ]);
  const MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES = /* @__PURE__ */ new Map([
    ["unispeech-sat", ["UniSpeechSatForAudioFrameClassification", UniSpeechSatForAudioFrameClassification]],
    ["wavlm", ["WavLMForAudioFrameClassification", WavLMForAudioFrameClassification]],
    ["wav2vec2", ["Wav2Vec2ForAudioFrameClassification", Wav2Vec2ForAudioFrameClassification]]
  ]);
  const MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES = /* @__PURE__ */ new Map([
    ["vitmatte", ["VitMatteForImageMatting", VitMatteForImageMatting]]
  ]);
  const MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES = /* @__PURE__ */ new Map([
    ["swin2sr", ["Swin2SRForImageSuperResolution", Swin2SRForImageSuperResolution]]
  ]);
  const MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES = /* @__PURE__ */ new Map([
    ["dpt", ["DPTForDepthEstimation", DPTForDepthEstimation]],
    ["depth_anything", ["DepthAnythingForDepthEstimation", DepthAnythingForDepthEstimation]],
    ["glpn", ["GLPNForDepthEstimation", GLPNForDepthEstimation]]
  ]);
  const MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES = /* @__PURE__ */ new Map([
    ["clip", ["CLIPVisionModelWithProjection", CLIPVisionModelWithProjection]],
    ["siglip", ["SiglipVisionModel", SiglipVisionModel]]
  ]);
  const MODEL_CLASS_TYPE_MAPPING = [
    [MODEL_MAPPING_NAMES_ENCODER_ONLY, MODEL_TYPES.EncoderOnly],
    [MODEL_MAPPING_NAMES_ENCODER_DECODER, MODEL_TYPES.EncoderDecoder],
    [MODEL_MAPPING_NAMES_DECODER_ONLY, MODEL_TYPES.DecoderOnly],
    [MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
    [MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
    [MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, MODEL_TYPES.Seq2Seq],
    [MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES, MODEL_TYPES.Seq2Seq],
    [MODEL_WITH_LM_HEAD_MAPPING_NAMES, MODEL_TYPES.DecoderOnly],
    [MODEL_FOR_MASKED_LM_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
    [MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
    [MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES, MODEL_TYPES.Vision2Seq],
    [MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
    [MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
    [MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
    [MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
    [MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
    [MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
    [MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
    [MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
    [MODEL_FOR_MASK_GENERATION_MAPPING_NAMES, MODEL_TYPES.MaskGeneration],
    [MODEL_FOR_CTC_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
    [MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
    [MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES, MODEL_TYPES.Seq2Seq],
    [MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
    [MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
    [MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly],
    // Custom:
    [MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES, MODEL_TYPES.EncoderOnly]
  ];
  for (const [mappings, type2] of MODEL_CLASS_TYPE_MAPPING) {
    for (const [name2, model] of mappings.values()) {
      MODEL_TYPE_MAPPING.set(name2, type2);
      MODEL_CLASS_TO_NAME_MAPPING.set(model, name2);
      MODEL_NAME_TO_CLASS_MAPPING.set(name2, model);
    }
  }
  const CUSTOM_MAPPING = [
    ["CLIPTextModelWithProjection", CLIPTextModelWithProjection, MODEL_TYPES.EncoderOnly],
    ["SiglipTextModel", SiglipTextModel, MODEL_TYPES.EncoderOnly],
    ["ClapTextModelWithProjection", ClapTextModelWithProjection, MODEL_TYPES.EncoderOnly],
    ["ClapAudioModelWithProjection", ClapAudioModelWithProjection, MODEL_TYPES.EncoderOnly]
  ];
  for (const [name2, model, type2] of CUSTOM_MAPPING) {
    MODEL_TYPE_MAPPING.set(name2, type2);
    MODEL_CLASS_TO_NAME_MAPPING.set(model, name2);
    MODEL_NAME_TO_CLASS_MAPPING.set(name2, model);
  }
  class AutoModel extends PretrainedMixin {
  }
  /** @type {Map<string, Object>[]} */
  // @ts-ignore
  __publicField2(AutoModel, "MODEL_CLASS_MAPPINGS", MODEL_CLASS_TYPE_MAPPING.map((x) => x[0]));
  __publicField2(AutoModel, "BASE_IF_FAIL", true);
  class Seq2SeqLMOutput extends ModelOutput {
    /**
     * @param {Object} output The output of the model.
     * @param {Tensor} output.logits The output logits of the model.
     * @param {Tensor} output.past_key_values An tensor of key/value pairs that represent the previous state of the model.
     * @param {Tensor} output.encoder_outputs The output of the encoder in a sequence-to-sequence model.
     * @param {Tensor} [output.decoder_attentions] Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the self-attention heads.
     * @param {Tensor} [output.cross_attentions] Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the weighted average in the cross-attention heads.
     */
    constructor({ logits, past_key_values, encoder_outputs, decoder_attentions = null, cross_attentions = null }) {
      super();
      this.logits = logits;
      this.past_key_values = past_key_values;
      this.encoder_outputs = encoder_outputs;
      this.decoder_attentions = decoder_attentions;
      this.cross_attentions = cross_attentions;
    }
  }
  class SequenceClassifierOutput extends ModelOutput {
    /**
     * @param {Object} output The output of the model.
     * @param {Tensor} output.logits classification (or regression if config.num_labels==1) scores (before SoftMax).
     */
    constructor({ logits }) {
      super();
      this.logits = logits;
    }
  }
  class XVectorOutput extends ModelOutput {
    /**
     * @param {Object} output The output of the model.
     * @param {Tensor} output.logits Classification hidden states before AMSoftmax, of shape `(batch_size, config.xvector_output_dim)`.
     * @param {Tensor} output.embeddings Utterance embeddings used for vector similarity-based retrieval, of shape `(batch_size, config.xvector_output_dim)`.
     */
    constructor({ logits, embeddings }) {
      super();
      this.logits = logits;
      this.embeddings = embeddings;
    }
  }
  class TokenClassifierOutput extends ModelOutput {
    /**
     * @param {Object} output The output of the model.
     * @param {Tensor} output.logits Classification scores (before SoftMax).
     */
    constructor({ logits }) {
      super();
      this.logits = logits;
    }
  }
  class MaskedLMOutput extends ModelOutput {
    /**
     * @param {Object} output The output of the model.
     * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
     */
    constructor({ logits }) {
      super();
      this.logits = logits;
    }
  }
  class QuestionAnsweringModelOutput extends ModelOutput {
    /**
     * @param {Object} output The output of the model.
     * @param {Tensor} output.start_logits Span-start scores (before SoftMax).
     * @param {Tensor} output.end_logits Span-end scores (before SoftMax).
     */
    constructor({ start_logits, end_logits }) {
      super();
      this.start_logits = start_logits;
      this.end_logits = end_logits;
    }
  }
  class CausalLMOutput extends ModelOutput {
    /**
     * @param {Object} output The output of the model.
     * @param {Tensor} output.logits Prediction scores of the language modeling head (scores for each vocabulary token before softmax).
     */
    constructor({ logits }) {
      super();
      this.logits = logits;
    }
  }
  class ImageMattingOutput extends ModelOutput {
    /**
     * @param {Object} output The output of the model.
     * @param {Tensor} output.alphas Estimated alpha values, of shape `(batch_size, num_channels, height, width)`.
     */
    constructor({ alphas }) {
      super();
      this.alphas = alphas;
    }
  }
  class VitsModelOutput extends ModelOutput {
    /**
     * @param {Object} output The output of the model.
     * @param {Tensor} output.waveform The final audio waveform predicted by the model, of shape `(batch_size, sequence_length)`.
     * @param {Tensor} output.spectrogram The log-mel spectrogram predicted at the output of the flow model.
     * This spectrogram is passed to the Hi-Fi GAN decoder model to obtain the final audio waveform.
     */
    constructor({ waveform, spectrogram }) {
      super();
      this.waveform = waveform;
      this.spectrogram = spectrogram;
    }
  }
  const BROWSER_ENV = typeof self !== "undefined";
  if (BROWSER_ENV) ;
  else if (sharp) ;
  else {
    throw new Error("Unable to load image processing library.");
  }
  const PREDEFINED_MODELS = {
    // Multilingual model - default recommendation
    "multilingual-e5-small": {
      modelIdentifier: "Xenova/multilingual-e5-small",
      dimension: 384,
      description: "Multilingual E5 Small - Lightweight multilingual model supporting 100+ languages",
      language: "multilingual",
      performance: "excellent",
      size: "116MB",
      // Quantized version
      latency: "20ms",
      multilingualFeatures: {
        languageSupport: "100+",
        crossLanguageRetrieval: "good",
        chineseEnglishMixed: "good"
      },
      modelSpecificConfig: {
        requiresTokenTypeIds: false
        // E5 model doesn't require token_type_ids
      }
    },
    "multilingual-e5-base": {
      modelIdentifier: "Xenova/multilingual-e5-base",
      dimension: 768,
      description: "Multilingual E5 base - Medium-scale multilingual model supporting 100+ languages",
      language: "multilingual",
      performance: "excellent",
      size: "279MB",
      // Quantized version
      latency: "30ms",
      multilingualFeatures: {
        languageSupport: "100+",
        crossLanguageRetrieval: "excellent",
        chineseEnglishMixed: "excellent"
      },
      modelSpecificConfig: {
        requiresTokenTypeIds: false
        // E5 model doesn't require token_type_ids
      }
    }
  };
  class SemanticSimilarityEngineProxy {
    // Flag to prevent concurrent ensureOffscreenEngineInitialized calls
    constructor(config2 = {}) {
      __publicField2(this, "_isInitialized", false);
      __publicField2(this, "config");
      __publicField2(this, "offscreenManager");
      __publicField2(this, "_isEnsuring", false);
      this.config = config2;
      this.offscreenManager = OffscreenManager.getInstance();
      console.log("SemanticSimilarityEngineProxy: Proxy created with config:", {
        modelPreset: config2.modelPreset,
        modelVersion: config2.modelVersion,
        dimension: config2.dimension
      });
    }
    initialize() {
      return __async(this, null, function* () {
        try {
          console.log("SemanticSimilarityEngineProxy: Starting proxy initialization...");
          console.log("SemanticSimilarityEngineProxy: Ensuring offscreen document exists...");
          yield this.offscreenManager.ensureOffscreenDocument();
          console.log("SemanticSimilarityEngineProxy: Offscreen document ready");
          console.log("SemanticSimilarityEngineProxy: Ensuring offscreen engine is initialized...");
          yield this.ensureOffscreenEngineInitialized();
          this._isInitialized = true;
          console.log(
            "SemanticSimilarityEngineProxy: Proxy initialized, delegating to offscreen engine"
          );
        } catch (error2) {
          console.error("SemanticSimilarityEngineProxy: Initialization failed:", error2);
          throw new Error(
            `Failed to initialize proxy: ${error2 instanceof Error ? error2.message : "Unknown error"}`
          );
        }
      });
    }
    /**
     * Check engine status in offscreen
     */
    checkOffscreenEngineStatus() {
      return __async(this, null, function* () {
        try {
          const response = yield chrome.runtime.sendMessage({
            target: "offscreen",
            type: OFFSCREEN_MESSAGE_TYPES.SIMILARITY_ENGINE_STATUS
          });
          if (response && response.success) {
            return {
              isInitialized: response.isInitialized || false,
              currentConfig: response.currentConfig || null
            };
          }
        } catch (error2) {
          console.warn("SemanticSimilarityEngineProxy: Failed to check engine status:", error2);
        }
        return { isInitialized: false, currentConfig: null };
      });
    }
    /**
     * Ensure engine in offscreen is initialized (with concurrency protection)
     */
    ensureOffscreenEngineInitialized() {
      return __async(this, null, function* () {
        if (this._isEnsuring) {
          console.log("SemanticSimilarityEngineProxy: Already ensuring initialization, waiting...");
          yield new Promise((resolve2) => setTimeout(resolve2, 100));
          return;
        }
        try {
          this._isEnsuring = true;
          const status = yield this.checkOffscreenEngineStatus();
          if (!status.isInitialized) {
            console.log(
              "SemanticSimilarityEngineProxy: Engine not initialized in offscreen, initializing..."
            );
            const response = yield chrome.runtime.sendMessage({
              target: "offscreen",
              type: OFFSCREEN_MESSAGE_TYPES.SIMILARITY_ENGINE_INIT,
              config: this.config
            });
            if (!response || !response.success) {
              throw new Error((response == null ? void 0 : response.error) || "Failed to initialize engine in offscreen document");
            }
            console.log("SemanticSimilarityEngineProxy: Engine reinitialized successfully");
          }
        } finally {
          this._isEnsuring = false;
        }
      });
    }
    /**
     * Send message to offscreen document with retry mechanism and auto-reinitialization
     */
    sendMessageToOffscreen(message, maxRetries = 3) {
      return __async(this, null, function* () {
        yield this.offscreenManager.ensureOffscreenDocument();
        let lastError = null;
        for (let attempt = 1; attempt <= maxRetries; attempt++) {
          try {
            console.log(
              `SemanticSimilarityEngineProxy: Sending message (attempt ${attempt}/${maxRetries}):`,
              message.type
            );
            const response = yield chrome.runtime.sendMessage(message);
            if (!response) {
              throw new Error("No response received from offscreen document");
            }
            if (!response.success && response.error && response.error.includes("not initialized")) {
              console.log(
                "SemanticSimilarityEngineProxy: Engine not initialized, attempting to reinitialize..."
              );
              yield this.ensureOffscreenEngineInitialized();
              const retryResponse = yield chrome.runtime.sendMessage(message);
              if (retryResponse && retryResponse.success) {
                return retryResponse;
              }
            }
            return response;
          } catch (error2) {
            lastError = error2;
            console.warn(
              `SemanticSimilarityEngineProxy: Message failed (attempt ${attempt}/${maxRetries}):`,
              error2
            );
            if (error2 instanceof Error && error2.message.includes("not initialized")) {
              try {
                console.log(
                  "SemanticSimilarityEngineProxy: Attempting to reinitialize engine due to error..."
                );
                yield this.ensureOffscreenEngineInitialized();
                const retryResponse = yield chrome.runtime.sendMessage(message);
                if (retryResponse && retryResponse.success) {
                  return retryResponse;
                }
              } catch (reinitError) {
                console.warn(
                  "SemanticSimilarityEngineProxy: Failed to reinitialize engine:",
                  reinitError
                );
              }
            }
            if (attempt < maxRetries) {
              yield new Promise((resolve2) => setTimeout(resolve2, 100 * attempt));
              try {
                yield this.offscreenManager.ensureOffscreenDocument();
              } catch (offscreenError) {
                console.warn(
                  "SemanticSimilarityEngineProxy: Failed to ensure offscreen document:",
                  offscreenError
                );
              }
            }
          }
        }
        throw new Error(
          `Failed to communicate with offscreen document after ${maxRetries} attempts. Last error: ${lastError == null ? void 0 : lastError.message}`
        );
      });
    }
    getEmbedding(_0) {
      return __async(this, arguments, function* (text, options = {}) {
        if (!this._isInitialized) {
          yield this.initialize();
        }
        yield this.ensureOffscreenEngineInitialized();
        const response = yield this.sendMessageToOffscreen({
          target: "offscreen",
          type: OFFSCREEN_MESSAGE_TYPES.SIMILARITY_ENGINE_COMPUTE,
          text,
          options
        });
        if (!response || !response.success) {
          throw new Error((response == null ? void 0 : response.error) || "Failed to get embedding from offscreen document");
        }
        if (!response.embedding || !Array.isArray(response.embedding)) {
          throw new Error("Invalid embedding data received from offscreen document");
        }
        return new Float32Array(response.embedding);
      });
    }
    getEmbeddingsBatch(_0) {
      return __async(this, arguments, function* (texts, options = {}) {
        if (!this._isInitialized) {
          yield this.initialize();
        }
        if (!texts || texts.length === 0) return [];
        yield this.ensureOffscreenEngineInitialized();
        const response = yield this.sendMessageToOffscreen({
          target: "offscreen",
          type: OFFSCREEN_MESSAGE_TYPES.SIMILARITY_ENGINE_BATCH_COMPUTE,
          texts,
          options
        });
        if (!response || !response.success) {
          throw new Error((response == null ? void 0 : response.error) || "Failed to get embeddings batch from offscreen document");
        }
        return response.embeddings.map((emb) => new Float32Array(emb));
      });
    }
    computeSimilarity(_0, _1) {
      return __async(this, arguments, function* (text1, text2, options = {}) {
        const [embedding1, embedding2] = yield this.getEmbeddingsBatch([text1, text2], options);
        return this.cosineSimilarity(embedding1, embedding2);
      });
    }
    computeSimilarityBatch(_0) {
      return __async(this, arguments, function* (pairs, options = {}) {
        if (!this._isInitialized) {
          yield this.initialize();
        }
        yield this.ensureOffscreenEngineInitialized();
        const response = yield this.sendMessageToOffscreen({
          target: "offscreen",
          type: OFFSCREEN_MESSAGE_TYPES.SIMILARITY_ENGINE_BATCH_COMPUTE,
          pairs,
          options
        });
        if (!response || !response.success) {
          throw new Error(
            (response == null ? void 0 : response.error) || "Failed to compute similarity batch from offscreen document"
          );
        }
        return response.similarities;
      });
    }
    cosineSimilarity(a, b) {
      if (a.length !== b.length) {
        throw new Error(`Vector dimensions don't match: ${a.length} vs ${b.length}`);
      }
      let dotProduct = 0;
      let normA = 0;
      let normB = 0;
      for (let i2 = 0; i2 < a.length; i2++) {
        dotProduct += a[i2] * b[i2];
        normA += a[i2] * a[i2];
        normB += b[i2] * b[i2];
      }
      const magnitude = Math.sqrt(normA) * Math.sqrt(normB);
      return magnitude === 0 ? 0 : dotProduct / magnitude;
    }
    get isInitialized() {
      return this._isInitialized;
    }
    dispose() {
      return __async(this, null, function* () {
        this._isInitialized = false;
        console.log("SemanticSimilarityEngineProxy: Proxy disposed");
      });
    }
  }
  class ContentIndexer {
    constructor(options) {
      __publicField2(this, "textChunker");
      __publicField2(this, "vectorDatabase");
      __publicField2(this, "semanticEngine");
      __publicField2(this, "isInitialized", false);
      __publicField2(this, "isInitializing", false);
      __publicField2(this, "initPromise", null);
      __publicField2(this, "indexedPages", /* @__PURE__ */ new Set());
      __publicField2(this, "options");
      this.options = __spreadValues({
        autoIndex: true,
        maxChunksPerPage: 50,
        skipDuplicates: true
      }, options);
      this.textChunker = new TextChunker();
    }
    /**
     * Get current selected model configuration
     */
    getCurrentModelConfig() {
      return __async(this, null, function* () {
        try {
          const result2 = yield chrome.storage.local.get(["selectedModel", "selectedVersion"]);
          const selectedModel = result2.selectedModel || "multilingual-e5-small";
          const selectedVersion = result2.selectedVersion || "quantized";
          const modelInfo = PREDEFINED_MODELS[selectedModel];
          return {
            modelPreset: selectedModel,
            modelIdentifier: modelInfo.modelIdentifier,
            dimension: modelInfo.dimension,
            modelVersion: selectedVersion,
            useLocalFiles: false,
            maxLength: 256,
            cacheSize: 1e3,
            forceOffscreen: true
          };
        } catch (error2) {
          console.error("ContentIndexer: Failed to get current model config, using default:", error2);
          return {
            modelPreset: "multilingual-e5-small",
            modelIdentifier: "Xenova/multilingual-e5-small",
            dimension: 384,
            modelVersion: "quantized",
            useLocalFiles: false,
            maxLength: 256,
            cacheSize: 1e3,
            forceOffscreen: true
          };
        }
      });
    }
    /**
     * Initialize content indexer
     */
    initialize() {
      return __async(this, null, function* () {
        if (this.isInitialized) return;
        if (this.isInitializing && this.initPromise) return this.initPromise;
        this.isInitializing = true;
        this.initPromise = this._doInitialize().finally(() => {
          this.isInitializing = false;
        });
        return this.initPromise;
      });
    }
    _doInitialize() {
      return __async(this, null, function* () {
        try {
          const engineConfig = yield this.getCurrentModelConfig();
          this.semanticEngine = new SemanticSimilarityEngineProxy(engineConfig);
          yield this.semanticEngine.initialize();
          this.vectorDatabase = yield getGlobalVectorDatabase({
            dimension: engineConfig.dimension,
            efSearch: 50
          });
          yield this.vectorDatabase.initialize();
          this.setupTabEventListeners();
          this.isInitialized = true;
        } catch (error2) {
          console.error("ContentIndexer: Initialization failed:", error2);
          this.isInitialized = false;
          throw error2;
        }
      });
    }
    /**
     * Index content of specified tab
     */
    indexTabContent(tabId) {
      return __async(this, null, function* () {
        if (!this.isSemanticEngineReady() && !this.isSemanticEngineInitializing()) {
          console.log(
            `ContentIndexer: Skipping tab ${tabId} - semantic engine not ready and not initializing`
          );
          return;
        }
        if (!this.isInitialized) {
          if (!this.isSemanticEngineReady()) {
            console.log(
              `ContentIndexer: Skipping tab ${tabId} - ContentIndexer not initialized and semantic engine not ready`
            );
            return;
          }
          yield this.initialize();
        }
        try {
          const tab = yield chrome.tabs.get(tabId);
          if (!tab.url || !this.shouldIndexUrl(tab.url)) {
            console.log(`ContentIndexer: Skipping tab ${tabId} - URL not indexable`);
            return;
          }
          const pageKey = `${tab.url}_${tab.title}`;
          if (this.options.skipDuplicates && this.indexedPages.has(pageKey)) {
            console.log(`ContentIndexer: Skipping tab ${tabId} - already indexed`);
            return;
          }
          console.log(`ContentIndexer: Starting to index tab ${tabId}: ${tab.title}`);
          const content = yield this.extractTabContent(tabId);
          if (!content) {
            console.log(`ContentIndexer: No content extracted from tab ${tabId}`);
            return;
          }
          const chunks = this.textChunker.chunkText(content.textContent, content.title);
          console.log(`ContentIndexer: Generated ${chunks.length} chunks for tab ${tabId}`);
          const chunksToIndex = chunks.slice(0, this.options.maxChunksPerPage);
          if (chunks.length > this.options.maxChunksPerPage) {
            console.log(
              `ContentIndexer: Limited chunks from ${chunks.length} to ${this.options.maxChunksPerPage}`
            );
          }
          for (const chunk of chunksToIndex) {
            try {
              const embedding = yield this.semanticEngine.getEmbedding(chunk.text);
              const label = yield this.vectorDatabase.addDocument(
                tabId,
                tab.url,
                tab.title || "",
                chunk,
                embedding
              );
              console.log(`ContentIndexer: Indexed chunk ${chunk.index} with label ${label}`);
            } catch (error2) {
              console.error(`ContentIndexer: Failed to index chunk ${chunk.index}:`, error2);
            }
          }
          this.indexedPages.add(pageKey);
          console.log(
            `ContentIndexer: Successfully indexed ${chunksToIndex.length} chunks for tab ${tabId}`
          );
        } catch (error2) {
          console.error(`ContentIndexer: Failed to index tab ${tabId}:`, error2);
        }
      });
    }
    /**
     * Search content
     */
    searchContent(query, topK = 10) {
      return __async(this, null, function* () {
        if (!this.isSemanticEngineReady() && !this.isSemanticEngineInitializing()) {
          throw new Error(
            "Semantic engine is not ready yet. Please initialize the semantic engine first."
          );
        }
        if (!this.isInitialized) {
          if (!this.isSemanticEngineReady()) {
            throw new Error(
              "ContentIndexer not initialized and semantic engine not ready. Please initialize the semantic engine first."
            );
          }
          yield this.initialize();
        }
        try {
          const queryEmbedding = yield this.semanticEngine.getEmbedding(query);
          const results = yield this.vectorDatabase.search(queryEmbedding, topK);
          console.log(`ContentIndexer: Found ${results.length} results for query: "${query}"`);
          return results;
        } catch (error2) {
          console.error("ContentIndexer: Search failed:", error2);
          if (error2 instanceof Error && error2.message.includes("not initialized")) {
            console.log(
              "ContentIndexer: Attempting to reinitialize semantic engine and retry search..."
            );
            try {
              yield this.semanticEngine.initialize();
              const queryEmbedding = yield this.semanticEngine.getEmbedding(query);
              const results = yield this.vectorDatabase.search(queryEmbedding, topK);
              console.log(
                `ContentIndexer: Retry successful, found ${results.length} results for query: "${query}"`
              );
              return results;
            } catch (retryError) {
              console.error("ContentIndexer: Retry after reinitialization also failed:", retryError);
              throw retryError;
            }
          }
          throw error2;
        }
      });
    }
    /**
     * Remove tab index
     */
    removeTabIndex(tabId) {
      return __async(this, null, function* () {
        if (!this.isInitialized) {
          return;
        }
        try {
          yield this.vectorDatabase.removeTabDocuments(tabId);
          for (const pageKey of this.indexedPages) {
            if (pageKey.includes(`tab_${tabId}_`)) {
              this.indexedPages.delete(pageKey);
            }
          }
          console.log(`ContentIndexer: Removed index for tab ${tabId}`);
        } catch (error2) {
          console.error(`ContentIndexer: Failed to remove index for tab ${tabId}:`, error2);
        }
      });
    }
    /**
     * Check if semantic engine is ready (checks both local and global state)
     */
    isSemanticEngineReady() {
      return this.semanticEngine && this.semanticEngine.isInitialized;
    }
    /**
     * Check if global semantic engine is ready (in background/offscreen)
     */
    isGlobalSemanticEngineReady() {
      return __async(this, null, function* () {
        try {
          const { handleGetModelStatus: handleGetModelStatus2 } = yield Promise.resolve().then(() => semanticSimilarity);
          const response = yield handleGetModelStatus2();
          return response && response.success && response.status && response.status.initializationStatus === "ready";
        } catch (error2) {
          console.error("ContentIndexer: Failed to check global semantic engine status:", error2);
          return false;
        }
      });
    }
    /**
     * Check if semantic engine is initializing
     */
    isSemanticEngineInitializing() {
      return this.isInitializing || this.semanticEngine && this.semanticEngine.isInitializing;
    }
    /**
     * Reinitialize content indexer (for model switching)
     */
    reinitialize() {
      return __async(this, null, function* () {
        console.log("ContentIndexer: Reinitializing for model switch...");
        this.isInitialized = false;
        this.isInitializing = false;
        this.initPromise = null;
        yield this.performCompleteDataCleanupForModelSwitch();
        this.indexedPages.clear();
        console.log("ContentIndexer: Cleared indexed pages cache");
        try {
          console.log("ContentIndexer: Creating new semantic engine proxy...");
          const newEngineConfig = yield this.getCurrentModelConfig();
          console.log("ContentIndexer: New engine config:", newEngineConfig);
          this.semanticEngine = new SemanticSimilarityEngineProxy(newEngineConfig);
          console.log("ContentIndexer: New semantic engine proxy created");
          yield this.semanticEngine.initialize();
          console.log("ContentIndexer: Semantic engine proxy initialization completed");
        } catch (error2) {
          console.error("ContentIndexer: Failed to create new semantic engine proxy:", error2);
          throw error2;
        }
        console.log(
          "ContentIndexer: New semantic engine proxy is ready, proceeding with initialization"
        );
        yield this.initialize();
        console.log("ContentIndexer: Reinitialization completed successfully");
      });
    }
    /**
     * Perform complete data cleanup for model switching
     */
    performCompleteDataCleanupForModelSwitch() {
      return __async(this, null, function* () {
        console.log("ContentIndexer: Starting complete data cleanup for model switch...");
        try {
          if (this.vectorDatabase) {
            try {
              console.log("ContentIndexer: Clearing existing vector database instance...");
              yield this.vectorDatabase.clear();
              console.log("ContentIndexer: Vector database instance cleared successfully");
            } catch (error2) {
              console.warn("ContentIndexer: Failed to clear vector database instance:", error2);
            }
          }
          try {
            const { clearAllVectorData: clearAllVectorData2 } = yield Promise.resolve().then(() => vectorDatabase);
            yield clearAllVectorData2();
            console.log("ContentIndexer: Cleared all vector data for model switch");
          } catch (error2) {
            console.warn("ContentIndexer: Failed to clear vector data:", error2);
          }
          try {
            const keysToRemove = [
              "hnswlib_document_mappings_tab_content_index.dat",
              "hnswlib_document_mappings_content_index.dat",
              "hnswlib_document_mappings_vector_index.dat",
              "vectorDatabaseStats",
              "lastCleanupTime"
            ];
            yield chrome.storage.local.remove(keysToRemove);
            console.log("ContentIndexer: Cleared chrome.storage model-related data");
          } catch (error2) {
            console.warn("ContentIndexer: Failed to clear chrome.storage data:", error2);
          }
          try {
            const deleteVectorDB = indexedDB.deleteDatabase("VectorDatabaseStorage");
            yield new Promise((resolve2) => {
              deleteVectorDB.onsuccess = () => {
                console.log("ContentIndexer: VectorDatabaseStorage database deleted");
                resolve2();
              };
              deleteVectorDB.onerror = () => {
                console.warn("ContentIndexer: Failed to delete VectorDatabaseStorage database");
                resolve2();
              };
              deleteVectorDB.onblocked = () => {
                console.warn("ContentIndexer: VectorDatabaseStorage database deletion blocked");
                resolve2();
              };
            });
            const deleteHnswDB = indexedDB.deleteDatabase("/hnswlib-index");
            yield new Promise((resolve2) => {
              deleteHnswDB.onsuccess = () => {
                console.log("ContentIndexer: /hnswlib-index database deleted");
                resolve2();
              };
              deleteHnswDB.onerror = () => {
                console.warn("ContentIndexer: Failed to delete /hnswlib-index database");
                resolve2();
              };
              deleteHnswDB.onblocked = () => {
                console.warn("ContentIndexer: /hnswlib-index database deletion blocked");
                resolve2();
              };
            });
            console.log("ContentIndexer: All IndexedDB databases cleared for model switch");
          } catch (error2) {
            console.warn("ContentIndexer: Failed to clear IndexedDB databases:", error2);
          }
          console.log("ContentIndexer: Complete data cleanup for model switch finished successfully");
        } catch (error2) {
          console.error("ContentIndexer: Complete data cleanup for model switch failed:", error2);
          throw error2;
        }
      });
    }
    /**
     * Manually trigger semantic engine initialization (async, don't wait for completion)
     * Note: This should only be called after the semantic engine is already initialized
     */
    startSemanticEngineInitialization() {
      if (!this.isInitialized && !this.isInitializing) {
        console.log("ContentIndexer: Checking if semantic engine is ready...");
        this.isGlobalSemanticEngineReady().then((isReady) => {
          if (isReady) {
            console.log("ContentIndexer: Starting initialization (semantic engine ready)...");
            this.initialize().catch((error2) => {
              console.error("ContentIndexer: Background initialization failed:", error2);
            });
          } else {
            console.log("ContentIndexer: Semantic engine not ready, skipping initialization");
          }
        }).catch((error2) => {
          console.error("ContentIndexer: Failed to check semantic engine status:", error2);
        });
      }
    }
    /**
     * Get indexing statistics
     */
    getStats() {
      const vectorStats = this.vectorDatabase ? this.vectorDatabase.getStats() : {
        totalDocuments: 0,
        totalTabs: 0,
        indexSize: 0
      };
      return __spreadProps(__spreadValues({}, vectorStats), {
        indexedPages: this.indexedPages.size,
        isInitialized: this.isInitialized,
        semanticEngineReady: this.isSemanticEngineReady(),
        semanticEngineInitializing: this.isSemanticEngineInitializing()
      });
    }
    /**
     * Clear all indexes
     */
    clearAllIndexes() {
      return __async(this, null, function* () {
        if (!this.isInitialized) {
          return;
        }
        try {
          yield this.vectorDatabase.clear();
          this.indexedPages.clear();
          console.log("ContentIndexer: All indexes cleared");
        } catch (error2) {
          console.error("ContentIndexer: Failed to clear indexes:", error2);
        }
      });
    }
    setupTabEventListeners() {
      chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => __async(this, null, function* () {
        if (this.options.autoIndex && changeInfo.status === "complete" && tab.url) {
          setTimeout(() => {
            if (!this.isSemanticEngineReady() && !this.isSemanticEngineInitializing()) {
              console.log(
                `ContentIndexer: Skipping auto-index for tab ${tabId} - semantic engine not ready`
              );
              return;
            }
            this.indexTabContent(tabId).catch((error2) => {
              console.error(`ContentIndexer: Auto-indexing failed for tab ${tabId}:`, error2);
            });
          }, 2e3);
        }
      }));
      chrome.tabs.onRemoved.addListener((tabId) => __async(this, null, function* () {
        yield this.removeTabIndex(tabId);
      }));
      if (chrome.webNavigation) {
        chrome.webNavigation.onCommitted.addListener((details) => __async(this, null, function* () {
          if (details.frameId === 0) {
            yield this.removeTabIndex(details.tabId);
          }
        }));
      }
    }
    shouldIndexUrl(url2) {
      const excludePatterns = [
        /^chrome:\/\//,
        /^chrome-extension:\/\//,
        /^edge:\/\//,
        /^about:/,
        /^moz-extension:\/\//,
        /^file:\/\//
      ];
      return !excludePatterns.some((pattern2) => pattern2.test(url2));
    }
    extractTabContent(tabId) {
      return __async(this, null, function* () {
        try {
          yield chrome.scripting.executeScript({
            target: { tabId },
            files: ["inject-scripts/web-fetcher-helper.js"]
          });
          const response = yield chrome.tabs.sendMessage(tabId, {
            action: TOOL_MESSAGE_TYPES.WEB_FETCHER_GET_TEXT_CONTENT
          });
          if (response.success && response.textContent) {
            return {
              textContent: response.textContent,
              title: response.title || ""
            };
          } else {
            console.error(
              `ContentIndexer: Failed to extract content from tab ${tabId}:`,
              response.error
            );
            return null;
          }
        } catch (error2) {
          console.error(`ContentIndexer: Error extracting content from tab ${tabId}:`, error2);
          return null;
        }
      });
    }
  }
  let globalContentIndexer = null;
  function getGlobalContentIndexer() {
    if (!globalContentIndexer) {
      globalContentIndexer = new ContentIndexer();
    }
    return globalContentIndexer;
  }
  const contentIndexer = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
    __proto__: null,
    ContentIndexer,
    getGlobalContentIndexer
  }, Symbol.toStringTag, { value: "Module" }));
  const STORAGE_KEYS = {
    IS_RECORDING: "isRecording",
    RECORDING: "recording",
    /** 已保存的录制列表 */
    MY_RECORDINGS: "myRecordings",
    /** 是否已显示过录制详情提示 */
    RECORDING_VIEW_HINT_SHOWN: "recordingViewHintShown",
    /** 控制是否自动跳转到录制详情页 */
    SHOULD_AUTO_NAVIGATE_TO_DETAIL: "shouldAutoNavigateToDetail",
    /** 待处理的服务器录制（从录制管理页面点击进入详情页时使用） */
    PENDING_SERVER_RECORDING: "pendingServerRecording",
    /** 待上传到服务器的录制数据（结束录制后等待上传） */
    PENDING_UPLOAD_RECORDING: "pendingUploadRecording"
  };
  const RECORDING_MESSAGE_TYPES = {
    START: "recording:start",
    STOP: "recording:stop",
    ADD_FLOW: "recording:add-flow",
    STATE_CHANGED: "recording:state-changed"
  };
  const RECORDING_BLOCKS = {
    trigger: {
      name: "Trigger",
      description: "Block where workflow will start executing",
      icon: "riFlashlightLine",
      category: "general",
      data: {
        disableBlock: false,
        description: "",
        type: "manual"
      }
    },
    "event-click": {
      name: "Click element",
      description: "Click on an element",
      icon: "riCursorLine",
      category: "interaction",
      data: {
        disableBlock: false,
        description: "",
        findBy: "cssSelector",
        waitForSelector: false,
        waitSelectorTimeout: 5e3,
        selector: "",
        markEl: false,
        multiple: false
      }
    },
    forms: {
      name: "Forms",
      description: "Manipulate form(input, select, checkbox, and radio) element",
      icon: "riInputCursorMove",
      category: "interaction",
      data: {
        disableBlock: false,
        description: "",
        findBy: "cssSelector",
        waitForSelector: false,
        waitSelectorTimeout: 5e3,
        selector: "",
        markEl: false,
        multiple: false,
        selected: true,
        clearValue: true,
        getValue: false,
        saveData: false,
        dataColumn: "",
        type: "text-field",
        value: "",
        delay: 0
      }
    },
    "press-key": {
      name: "Press key",
      description: "Press keyboard key",
      icon: "riKeyboardLine",
      category: "interaction",
      data: {
        disableBlock: false,
        description: "",
        keys: "",
        selector: ""
      }
    },
    "element-scroll": {
      name: "Scroll element",
      description: "Scroll page or element",
      icon: "riMouseLine",
      category: "interaction",
      data: {
        disableBlock: false,
        description: "",
        findBy: "cssSelector",
        waitForSelector: false,
        waitSelectorTimeout: 5e3,
        selector: "html",
        markEl: false,
        multiple: false,
        scrollY: 0,
        scrollX: 0,
        smooth: false
      }
    },
    "new-tab": {
      name: "New tab",
      description: "Create a new tab",
      icon: "riGlobalLine",
      category: "browser",
      data: {
        disableBlock: false,
        description: "",
        url: "",
        active: true,
        waitTabLoaded: false,
        updatePrevTab: false
      }
    },
    "switch-tab": {
      name: "Switch tab",
      description: "Switch active tab",
      icon: "riArrowLeftRightLine",
      category: "browser",
      data: {
        disableBlock: false,
        description: "",
        url: "",
        matchPattern: "",
        activeTab: true,
        createIfNoMatch: false
      }
    },
    link: {
      name: "Link",
      description: "Open link element",
      icon: "riLink",
      category: "interaction",
      data: {
        disableBlock: false,
        description: "",
        findBy: "cssSelector",
        waitForSelector: false,
        waitSelectorTimeout: 5e3,
        selector: "",
        markEl: false,
        openInNewTab: false
      }
    },
    "upload-file": {
      name: "Upload file",
      description: "Upload file to input element",
      icon: "riUpload2Line",
      category: "interaction",
      data: {
        disableBlock: false,
        description: "",
        selector: "",
        waitForSelector: true,
        filePaths: []
      }
    },
    "trigger-event": {
      name: "Trigger event",
      description: "Trigger event on element",
      icon: "riLightbulbFlashLine",
      category: "interaction",
      data: {
        disableBlock: false,
        description: "",
        findBy: "cssSelector",
        waitForSelector: false,
        waitSelectorTimeout: 5e3,
        selector: "html",
        markEl: false,
        multiple: false,
        eventName: "",
        eventType: "",
        eventParams: { bubbles: true, cancelable: false }
      }
    }
  };
  function getBlockDefaultData(blockId) {
    var _a3, _b2;
    return (_b2 = (_a3 = RECORDING_BLOCKS[blockId]) == null ? void 0 : _a3.data) != null ? _b2 : {};
  }
  const index$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
    __proto__: null,
    RECORDING_BLOCKS,
    RECORDING_MESSAGE_TYPES,
    STORAGE_KEYS,
    getBlockDefaultData
  }, Symbol.toStringTag, { value: "Module" }));
  let lastActivatedTabId = -1;
  function setLastActivatedTabId(tabId) {
    lastActivatedTabId = tabId;
  }
  function updateRecording(callback) {
    return __async(this, null, function* () {
      try {
        const result2 = yield chrome.storage.local.get([
          STORAGE_KEYS.IS_RECORDING,
          STORAGE_KEYS.RECORDING
        ]);
        if (!result2[STORAGE_KEYS.IS_RECORDING] || !result2[STORAGE_KEYS.RECORDING]) {
          return;
        }
        const recording = result2[STORAGE_KEYS.RECORDING];
        callback(recording);
        yield chrome.storage.local.set({ [STORAGE_KEYS.RECORDING]: recording });
      } catch (error2) {
        console.error("[Recording] updateRecording failed:", error2);
      }
    });
  }
  const validateUrl = (url2) => {
    var _a3;
    return (_a3 = url2 == null ? void 0 : url2.startsWith("http")) != null ? _a3 : false;
  };
  function onTabCreated(tab) {
    updateRecording((recording) => {
      var _a3, _b2;
      const url2 = tab.url || tab.pendingUrl || "";
      const lastFlow = recording.flows[recording.flows.length - 1];
      const isInvalidPrevFlow = (lastFlow == null ? void 0 : lastFlow.id) === "new-tab" && !validateUrl(lastFlow.data.url);
      if (!isInvalidPrevFlow) {
        const validUrl = validateUrl(url2) ? url2 : "";
        recording.flows.push({
          id: "new-tab",
          autoDescription: `导航至 ${validUrl}`,
          timestamp: Date.now(),
          tabId: (_a3 = tab.id) != null ? _a3 : -1,
          data: {
            url: validUrl
          }
        });
      }
      recording.activeTab = {
        url: url2,
        id: (_b2 = tab.id) != null ? _b2 : -1
      };
    });
  }
  function onTabsActivated(activeInfo) {
    return __async(this, null, function* () {
      try {
        console.log("[Recording] onTabsActivated triggered:", activeInfo.tabId);
        const tab = yield chrome.tabs.get(activeInfo.tabId);
        console.log("[Recording] onTabsActivated tab:", tab.id, tab.url);
        if (!validateUrl(tab.url)) {
          console.log("[Recording] onTabsActivated: URL validation failed");
          return;
        }
        yield updateRecording((recording) => {
          var _a3;
          console.log("[Recording] onTabsActivated: checking lastActivatedTabId", lastActivatedTabId);
          if (lastActivatedTabId === tab.id) {
            console.log("[Recording] onTabsActivated: duplicate activation, skipping");
            return;
          }
          console.log("[Recording] onTabsActivated: adding flow for tab", tab.id, tab.url);
          recording.activeTab = { id: tab.id, url: tab.url };
          recording.flows.push({
            id: "new-tab",
            autoDescription: `导航至 ${tab.url}`,
            timestamp: Date.now(),
            tabId: (_a3 = tab.id) != null ? _a3 : -1,
            data: {
              url: tab.url
            }
          });
          lastActivatedTabId = tab.id;
          console.log("[Recording] onTabsActivated: flow added successfully");
        });
      } catch (error2) {
        console.error("[Recording] onTabsActivated error:", error2);
      }
    });
  }
  function onWebNavigationCommitted(details) {
    const allowedTypes = ["link", "typed"];
    if (details.frameId !== 0 || !allowedTypes.includes(details.transitionType)) {
      return;
    }
    updateRecording((recording) => {
      if (recording.activeTab.id && details.tabId !== recording.activeTab.id) {
        return;
      }
      const lastFlow = recording.flows[recording.flows.length - 1];
      const isInvalidNewTabFlow = (lastFlow == null ? void 0 : lastFlow.id) === "new-tab" && !validateUrl(lastFlow.data.url);
      if (isInvalidNewTabFlow) {
        lastFlow.data.url = details.url;
        lastFlow.autoDescription = `导航至 ${details.url}`;
      } else if (validateUrl(details.url)) {
        if ((lastFlow == null ? void 0 : lastFlow.id) !== "link") {
          recording.flows.push({
            id: "new-tab",
            autoDescription: `导航至 ${details.url}`,
            timestamp: Date.now(),
            tabId: details.tabId,
            data: {
              url: details.url,
              updatePrevTab: recording.activeTab.id === details.tabId
            }
          });
        }
        recording.activeTab.id = details.tabId;
        recording.activeTab.url = details.url;
      }
    });
  }
  function onWebNavigationCompleted(details) {
    return __async(this, null, function* () {
      if (details.frameId > 0 || !details.url.startsWith("http")) {
        return;
      }
      try {
        const result2 = yield chrome.storage.local.get(STORAGE_KEYS.IS_RECORDING);
        if (!result2[STORAGE_KEYS.IS_RECORDING]) return;
        yield chrome.tabs.sendMessage(details.tabId, {
          type: RECORDING_MESSAGE_TYPES.START
        });
      } catch (error2) {
        console.debug("[Recording] onWebNavigationCompleted: content script not ready");
      }
    });
  }
  function registerRecordingEventListeners() {
    lastActivatedTabId = -1;
    chrome.tabs.onCreated.addListener(onTabCreated);
    chrome.tabs.onActivated.addListener(onTabsActivated);
    chrome.webNavigation.onCommitted.addListener(onWebNavigationCommitted);
    chrome.webNavigation.onCompleted.addListener(onWebNavigationCompleted);
    console.error("[Recording] Event listeners registered");
  }
  function unregisterRecordingEventListeners() {
    chrome.tabs.onCreated.removeListener(onTabCreated);
    chrome.tabs.onActivated.removeListener(onTabsActivated);
    chrome.webNavigation.onCommitted.removeListener(onWebNavigationCommitted);
    chrome.webNavigation.onCompleted.removeListener(onWebNavigationCompleted);
    lastActivatedTabId = -1;
    console.log("[Recording] Event listeners unregistered");
  }
  function startRecording() {
    return __async(this, arguments, function* (options = {}) {
      var _a3, _b2, _c2, _d2, _e, _f;
      try {
        const [activeTab] = yield browser$1.tabs.query({
          active: true,
          lastFocusedWindow: true,
          url: "*://*/*"
        });
        const flows = [];
        if ((_a3 = activeTab == null ? void 0 : activeTab.url) == null ? void 0 : _a3.startsWith("http")) {
          setLastActivatedTabId((_b2 = activeTab.id) != null ? _b2 : -1);
          flows.push({
            id: "new-tab",
            autoDescription: `导航至 ${activeTab.url}`,
            timestamp: Date.now(),
            tabId: (_c2 = activeTab.id) != null ? _c2 : -1,
            data: { url: activeTab.url }
          });
          if (activeTab.windowId) {
            yield browser$1.windows.update(activeTab.windowId, { focused: true });
          }
        }
        const recording = {
          isRecording: true,
          name: options.name || "unnamed",
          flows,
          activeTab: {
            id: (_d2 = activeTab == null ? void 0 : activeTab.id) != null ? _d2 : -1,
            url: (_e = activeTab == null ? void 0 : activeTab.url) != null ? _e : ""
          }
        };
        yield browser$1.storage.local.set({
          [STORAGE_KEYS.IS_RECORDING]: true,
          [STORAGE_KEYS.RECORDING]: recording
        });
        yield browser$1.action.setBadgeBackgroundColor({ color: "#ef4444" });
        yield browser$1.action.setBadgeText({ text: "rec" });
        const tabs = yield browser$1.tabs.query({});
        for (const tab of tabs) {
          if (tab.id && ((_f = tab.url) == null ? void 0 : _f.startsWith("http")) && !tab.url.includes("chrome.google.com")) {
            try {
              yield browser$1.tabs.sendMessage(tab.id, { type: RECORDING_MESSAGE_TYPES.START });
            } catch (e) {
            }
          }
        }
        console.log("[Recording] Started recording");
      } catch (error2) {
        console.error("[Recording] Failed to start recording:", error2);
        throw error2;
      }
    });
  }
  function stopRecording() {
    return __async(this, null, function* () {
      try {
        const result2 = yield browser$1.storage.local.get([
          STORAGE_KEYS.IS_RECORDING,
          STORAGE_KEYS.RECORDING
        ]);
        if (!result2[STORAGE_KEYS.IS_RECORDING]) {
          return null;
        }
        const recording = result2[STORAGE_KEYS.RECORDING];
        yield browser$1.storage.local.set({
          [STORAGE_KEYS.RECORDING]: recording
        });
        yield browser$1.action.setBadgeText({ text: "" });
        const tabs = yield browser$1.tabs.query({});
        yield Promise.allSettled(
          tabs.filter((tab) => {
            var _a3;
            return tab.id && ((_a3 = tab.url) == null ? void 0 : _a3.startsWith("http"));
          }).map(
            (tab) => browser$1.tabs.sendMessage(tab.id, { type: RECORDING_MESSAGE_TYPES.STOP }).catch(() => {
            })
          )
        );
        console.log("[Recording] Stopped recording, flows:", recording.flows.length);
        return recording;
      } catch (error2) {
        console.error("[Recording] Failed to stop recording:", error2);
        throw error2;
      }
    });
  }
  function clearRecording() {
    return __async(this, null, function* () {
      yield browser$1.storage.local.remove([STORAGE_KEYS.IS_RECORDING, STORAGE_KEYS.RECORDING]);
      console.log("[Recording] Cleared recording data");
    });
  }
  function getRecordingState() {
    return __async(this, null, function* () {
      const result2 = yield browser$1.storage.local.get([
        STORAGE_KEYS.IS_RECORDING,
        STORAGE_KEYS.RECORDING
      ]);
      if (!result2[STORAGE_KEYS.IS_RECORDING]) {
        return null;
      }
      return result2[STORAGE_KEYS.RECORDING];
    });
  }
  function nanoid() {
    return crypto.randomUUID().replace(/-/g, "").slice(0, 12);
  }
  function mergeBlockData(blockId, data) {
    const defaultData = getBlockDefaultData(blockId);
    return __spreadValues(__spreadValues({}, defaultData), data);
  }
  function convertFlowsToDrawflow(flows, name2, description2) {
    const nodes = [];
    const edges = [];
    const triggerId = nanoid();
    nodes.push({
      id: triggerId,
      label: "trigger",
      type: "BlockBasic",
      data: { type: "manual", disableBlock: false },
      position: { x: 50, y: 300 }
    });
    let prevNodeId = triggerId;
    let positionX = 320;
    const positionY = 300;
    const groupedBlocks = /* @__PURE__ */ new Map();
    for (let i2 = 0; i2 < flows.length; i2++) {
      const flow = flows[i2];
      if (flow.groupId) {
        const group = groupedBlocks.get(flow.groupId) || [];
        group.push(flow);
        groupedBlocks.set(flow.groupId, group);
        const nextFlow = flows[i2 + 1];
        if ((nextFlow == null ? void 0 : nextFlow.groupId) === flow.groupId) {
          continue;
        }
        const groupFlows = groupedBlocks.get(flow.groupId);
        const blocks = groupFlows.map((f) => {
          return {
            id: f.id,
            itemId: nanoid(),
            data: mergeBlockData(f.id, __spreadProps(__spreadValues({}, f.data), {
              description: f.userNote || "",
              autoDescription: f.autoDescription || ""
            }))
          };
        });
        const nodeId2 = nanoid();
        nodes.push({
          id: nodeId2,
          label: "blocks-group",
          type: "BlockBasic",
          data: { blocks },
          position: { x: positionX, y: positionY }
        });
        edges.push({
          id: nanoid(),
          source: prevNodeId,
          target: nodeId2,
          sourceHandle: `${prevNodeId}-output-1`,
          targetHandle: `${nodeId2}-input-1`
        });
        prevNodeId = nodeId2;
        positionX += 280;
        groupedBlocks.delete(flow.groupId);
        continue;
      }
      const nodeId = nanoid();
      const componentType = "BlockBasic";
      nodes.push({
        id: nodeId,
        label: flow.id,
        type: componentType,
        data: mergeBlockData(flow.id, __spreadProps(__spreadValues({}, flow.data), {
          description: flow.userNote || "",
          autoDescription: flow.autoDescription || ""
        })),
        position: { x: positionX, y: positionY }
      });
      edges.push({
        id: nanoid(),
        source: prevNodeId,
        target: nodeId,
        sourceHandle: `${prevNodeId}-output-1`,
        targetHandle: `${nodeId}-input-1`
      });
      prevNodeId = nodeId;
      positionX += 280;
      if ((nodes.length - 1) % 5 === 0) {
        positionX = 50;
      }
    }
    const drawflow = {
      nodes,
      edges
    };
    return {
      name: name2,
      description: description2 || "",
      drawflow
    };
  }
  function exportToAutomaJson(workflow) {
    return JSON.stringify(workflow, null, 2);
  }
  const index = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
    __proto__: null,
    clearRecording,
    convertFlowsToDrawflow,
    exportToAutomaJson,
    getRecordingState,
    onTabCreated,
    onTabsActivated,
    onWebNavigationCommitted,
    onWebNavigationCompleted,
    registerRecordingEventListeners,
    setLastActivatedTabId,
    startRecording,
    stopRecording,
    unregisterRecordingEventListeners
  }, Symbol.toStringTag, { value: "Module" }));
  var __defProp = Object.defineProperty;
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  var __publicField = (obj, key, value) => {
    __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
    return value;
  };
  var hnswlib$1 = /* @__PURE__ */ (() => {
    return function() {
      return __async(this, arguments, function* (moduleArg = {}) {
        var moduleRtn;
        var Module = moduleArg;
        var readyPromiseResolve, readyPromiseReject;
        var readyPromise = new Promise((resolve2, reject) => {
          readyPromiseResolve = resolve2;
          readyPromiseReject = reject;
        });
        var thisProgram = "./this.program";
        var _scriptName = self.location.href;
        var scriptDirectory = "";
        function locateFile(path) {
          if (Module["locateFile"]) {
            return Module["locateFile"](path, scriptDirectory);
          }
          return scriptDirectory + path;
        }
        var readAsync, readBinary;
        {
          try {
            scriptDirectory = new URL(".", _scriptName).href;
          } catch (e) {
          }
          if (!(typeof window == "object" || typeof WorkerGlobalScope != "undefined"))
            throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)");
          {
            readAsync = (url2) => __async(null, null, function* () {
              assert2(!isFileURI(url2), "readAsync does not work with file:// URLs");
              var response = yield fetch(url2, { credentials: "same-origin" });
              if (response.ok) {
                return response.arrayBuffer();
              }
              throw new Error(response.status + " : " + response.url);
            });
          }
        }
        var out = console.log.bind(console);
        var err = console.error.bind(console);
        var IDBFS = "IDBFS is no longer included by default; build with -lidbfs.js";
        assert2(true, "worker environment detected but not enabled at build time.  Add `worker` to `-sENVIRONMENT` to enable.");
        assert2(true, "node environment detected but not enabled at build time.  Add `node` to `-sENVIRONMENT` to enable.");
        assert2(true, "shell environment detected but not enabled at build time.  Add `shell` to `-sENVIRONMENT` to enable.");
        var wasmBinary;
        if (typeof WebAssembly != "object") {
          err("no native wasm support detected");
        }
        var wasmMemory;
        var ABORT = false;
        function assert2(condition, text) {
          if (!condition) {
            abort("Assertion failed" + (text ? ": " + text : ""));
          }
        }
        var HEAP8, HEAPU8, HEAP16, HEAPU16, HEAP32, HEAPU32, HEAPF32, HEAP64, HEAPU64, HEAPF64;
        var runtimeInitialized = false;
        var isFileURI = (filename) => filename.startsWith("file://");
        function writeStackCookie() {
          var max2 = _emscripten_stack_get_end();
          assert2((max2 & 3) == 0);
          if (max2 == 0) {
            max2 += 4;
          }
          HEAPU32[max2 >> 2] = 34821223;
          HEAPU32[max2 + 4 >> 2] = 2310721022;
          HEAPU32[0 >> 2] = 1668509029;
        }
        function checkStackCookie() {
          if (ABORT)
            return;
          var max2 = _emscripten_stack_get_end();
          if (max2 == 0) {
            max2 += 4;
          }
          var cookie1 = HEAPU32[max2 >> 2];
          var cookie2 = HEAPU32[max2 + 4 >> 2];
          if (cookie1 != 34821223 || cookie2 != 2310721022) {
            abort(`Stack overflow! Stack cookie has been overwritten at ${ptrToString(max2)}, expected hex dwords 0x89BACDFE and 0x2135467, but received ${ptrToString(cookie2)} ${ptrToString(cookie1)}`);
          }
          if (HEAPU32[0 >> 2] != 1668509029) {
            abort("Runtime error: The application has corrupted its heap memory area (address zero)!");
          }
        }
        (() => {
          var h16 = new Int16Array(1);
          var h8 = new Int8Array(h16.buffer);
          h16[0] = 25459;
          if (h8[0] !== 115 || h8[1] !== 99)
            throw "Runtime error: expected the system to be little-endian! (Run with -sSUPPORT_BIG_ENDIAN to bypass)";
        })();
        function consumedModuleProp(prop) {
          if (!Object.getOwnPropertyDescriptor(Module, prop)) {
            Object.defineProperty(Module, prop, {
              configurable: true,
              set() {
                abort(`Attempt to set \`Module.${prop}\` after it has already been processed.  This can happen, for example, when code is injected via '--post-js' rather than '--pre-js'`);
              }
            });
          }
        }
        function ignoredModuleProp(prop) {
          if (Object.getOwnPropertyDescriptor(Module, prop)) {
            abort(`\`Module.${prop}\` was supplied but \`${prop}\` not included in INCOMING_MODULE_JS_API`);
          }
        }
        function isExportedByForceFilesystem(name2) {
          return name2 === "FS_createPath" || name2 === "FS_createDataFile" || name2 === "FS_createPreloadedFile" || name2 === "FS_unlink" || name2 === "addRunDependency" || // The old FS has some functionality that WasmFS lacks.
          name2 === "FS_createLazyFile" || name2 === "FS_createDevice" || name2 === "removeRunDependency";
        }
        function hookGlobalSymbolAccess(sym, func) {
          if (typeof globalThis != "undefined" && !Object.getOwnPropertyDescriptor(globalThis, sym)) {
            Object.defineProperty(globalThis, sym, {
              configurable: true,
              get() {
                func();
                return void 0;
              }
            });
          }
        }
        function missingGlobal(sym, msg) {
          hookGlobalSymbolAccess(sym, () => {
            warnOnce(`\`${sym}\` is not longer defined by emscripten. ${msg}`);
          });
        }
        missingGlobal("buffer", "Please use HEAP8.buffer or wasmMemory.buffer");
        missingGlobal("asm", "Please use wasmExports instead");
        function missingLibrarySymbol(sym) {
          hookGlobalSymbolAccess(sym, () => {
            var msg = `\`${sym}\` is a library symbol and not included by default; add it to your library.js __deps or to DEFAULT_LIBRARY_FUNCS_TO_INCLUDE on the command line`;
            var librarySymbol = sym;
            if (!librarySymbol.startsWith("_")) {
              librarySymbol = "$" + sym;
            }
            msg += ` (e.g. -sDEFAULT_LIBRARY_FUNCS_TO_INCLUDE='${librarySymbol}')`;
            if (isExportedByForceFilesystem(sym)) {
              msg += ". Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you";
            }
            warnOnce(msg);
          });
          unexportedRuntimeSymbol(sym);
        }
        function unexportedRuntimeSymbol(sym) {
          if (!Object.getOwnPropertyDescriptor(Module, sym)) {
            Object.defineProperty(Module, sym, {
              configurable: true,
              get() {
                var msg = `'${sym}' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the Emscripten FAQ)`;
                if (isExportedByForceFilesystem(sym)) {
                  msg += ". Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you";
                }
                abort(msg);
              }
            });
          }
        }
        function updateMemoryViews() {
          var b = wasmMemory.buffer;
          HEAP8 = new Int8Array(b);
          HEAP16 = new Int16Array(b);
          HEAPU8 = new Uint8Array(b);
          HEAPU16 = new Uint16Array(b);
          HEAP32 = new Int32Array(b);
          HEAPU32 = new Uint32Array(b);
          HEAPF32 = new Float32Array(b);
          HEAPF64 = new Float64Array(b);
          HEAP64 = new BigInt64Array(b);
          HEAPU64 = new BigUint64Array(b);
        }
        assert2(
          typeof Int32Array != "undefined" && typeof Float64Array !== "undefined" && Int32Array.prototype.subarray != void 0 && Int32Array.prototype.set != void 0,
          "JS engine does not provide full typed array support"
        );
        function preRun() {
          if (Module["preRun"]) {
            if (typeof Module["preRun"] == "function")
              Module["preRun"] = [Module["preRun"]];
            while (Module["preRun"].length) {
              addOnPreRun(Module["preRun"].shift());
            }
          }
          consumedModuleProp("preRun");
          callRuntimeCallbacks(onPreRuns);
        }
        function initRuntime() {
          assert2(!runtimeInitialized);
          runtimeInitialized = true;
          checkStackCookie();
          if (!Module["noFSInit"] && !FS.initialized)
            FS.init();
          wasmExports["__wasm_call_ctors"]();
          FS.ignorePermissions = false;
        }
        function postRun() {
          checkStackCookie();
          if (Module["postRun"]) {
            if (typeof Module["postRun"] == "function")
              Module["postRun"] = [Module["postRun"]];
            while (Module["postRun"].length) {
              addOnPostRun(Module["postRun"].shift());
            }
          }
          consumedModuleProp("postRun");
          callRuntimeCallbacks(onPostRuns);
        }
        var runDependencies = 0;
        var dependenciesFulfilled = null;
        var runDependencyTracking = {};
        var runDependencyWatcher = null;
        function getUniqueRunDependency(id2) {
          var orig = id2;
          while (1) {
            if (!runDependencyTracking[id2])
              return id2;
            id2 = orig + Math.random();
          }
        }
        function addRunDependency(id2) {
          var _a3;
          runDependencies++;
          (_a3 = Module["monitorRunDependencies"]) == null ? void 0 : _a3.call(Module, runDependencies);
          if (id2) {
            assert2(!runDependencyTracking[id2]);
            runDependencyTracking[id2] = 1;
            if (runDependencyWatcher === null && typeof setInterval != "undefined") {
              runDependencyWatcher = setInterval(() => {
                if (ABORT) {
                  clearInterval(runDependencyWatcher);
                  runDependencyWatcher = null;
                  return;
                }
                var shown = false;
                for (var dep in runDependencyTracking) {
                  if (!shown) {
                    shown = true;
                    err("still waiting on run dependencies:");
                  }
                  err(`dependency: ${dep}`);
                }
                if (shown) {
                  err("(end of list)");
                }
              }, 1e4);
            }
          } else {
            err("warning: run dependency added without ID");
          }
        }
        function removeRunDependency(id2) {
          var _a3;
          runDependencies--;
          (_a3 = Module["monitorRunDependencies"]) == null ? void 0 : _a3.call(Module, runDependencies);
          if (id2) {
            assert2(runDependencyTracking[id2]);
            delete runDependencyTracking[id2];
          } else {
            err("warning: run dependency removed without ID");
          }
          if (runDependencies == 0) {
            if (runDependencyWatcher !== null) {
              clearInterval(runDependencyWatcher);
              runDependencyWatcher = null;
            }
            if (dependenciesFulfilled) {
              var callback = dependenciesFulfilled;
              dependenciesFulfilled = null;
              callback();
            }
          }
        }
        function abort(what) {
          var _a3;
          (_a3 = Module["onAbort"]) == null ? void 0 : _a3.call(Module, what);
          what = "Aborted(" + what + ")";
          err(what);
          ABORT = true;
          if (runtimeInitialized) {
            ___trap();
          }
          var e = new WebAssembly.RuntimeError(what);
          readyPromiseReject(e);
          throw e;
        }
        function createExportWrapper(name2, nargs) {
          return (...args) => {
            assert2(runtimeInitialized, `native function \`${name2}\` called before runtime initialization`);
            var f = wasmExports[name2];
            assert2(f, `exported native function \`${name2}\` not found`);
            assert2(args.length <= nargs, `native function \`${name2}\` called with ${args.length} args but expects ${nargs}`);
            return f(...args);
          };
        }
        var wasmBinaryFile;
        function findWasmBinary() {
          if (Module["locateFile"]) {
            return locateFile("hnswlib.wasm");
          }
          return new URL("data:application/wasm;base64, ", self.location).href;
        }
        function getBinarySync(file2) {
          if (file2 == wasmBinaryFile && wasmBinary) {
            return new Uint8Array(wasmBinary);
          }
          throw "both async and sync fetching of the wasm failed";
        }
        function getWasmBinary(binaryFile) {
          return __async(this, null, function* () {
            if (!wasmBinary) {
              try {
                var response = yield readAsync(binaryFile);
                return new Uint8Array(response);
              } catch (e) {
              }
            }
            return getBinarySync(binaryFile);
          });
        }
        function instantiateArrayBuffer(binaryFile, imports) {
          return __async(this, null, function* () {
            try {
              var binary = yield getWasmBinary(binaryFile);
              var instance2 = yield WebAssembly.instantiate(binary, imports);
              return instance2;
            } catch (reason) {
              err(`failed to asynchronously prepare wasm: ${reason}`);
              if (isFileURI(wasmBinaryFile)) {
                err(`warning: Loading from a file URI (${wasmBinaryFile}) is not supported in most browsers. See https://emscripten.org/docs/getting_started/FAQ.html#how-do-i-run-a-local-webserver-for-testing-why-does-my-program-stall-in-downloading-or-preparing`);
              }
              abort(reason);
            }
          });
        }
        function instantiateAsync(binary, binaryFile, imports) {
          return __async(this, null, function* () {
            if (!binary && typeof WebAssembly.instantiateStreaming == "function") {
              try {
                var response = fetch(binaryFile, { credentials: "same-origin" });
                var instantiationResult = yield WebAssembly.instantiateStreaming(response, imports);
                return instantiationResult;
              } catch (reason) {
                err(`wasm streaming compile failed: ${reason}`);
                err("falling back to ArrayBuffer instantiation");
              }
            }
            return instantiateArrayBuffer(binaryFile, imports);
          });
        }
        function getWasmImports() {
          return {
            "env": wasmImports,
            "wasi_snapshot_preview1": wasmImports
          };
        }
        function createWasm() {
          return __async(this, null, function* () {
            function receiveInstance(instance2, module2) {
              wasmExports = instance2.exports;
              wasmMemory = wasmExports["memory"];
              assert2(wasmMemory, "memory not found in wasm exports");
              updateMemoryViews();
              wasmTable = wasmExports["__indirect_function_table"];
              assert2(wasmTable, "table not found in wasm exports");
              ___cpp_exception = wasmExports["__cpp_exception"];
              removeRunDependency("wasm-instantiate");
              return wasmExports;
            }
            addRunDependency("wasm-instantiate");
            var trueModule = Module;
            function receiveInstantiationResult(result22) {
              assert2(Module === trueModule, "the Module object should not be replaced during async compilation - perhaps the order of HTML elements is wrong?");
              trueModule = null;
              return receiveInstance(result22["instance"]);
            }
            var info = getWasmImports();
            if (Module["instantiateWasm"]) {
              return new Promise((resolve2, reject) => {
                try {
                  Module["instantiateWasm"](info, (mod2, inst) => {
                    resolve2(receiveInstance(mod2, inst));
                  });
                } catch (e) {
                  err(`Module.instantiateWasm callback failed with error: ${e}`);
                  reject(e);
                }
              });
            }
            wasmBinaryFile != null ? wasmBinaryFile : wasmBinaryFile = findWasmBinary();
            try {
              var result2 = yield instantiateAsync(wasmBinary, wasmBinaryFile, info);
              var exports$12 = receiveInstantiationResult(result2);
              return exports$12;
            } catch (e) {
              readyPromiseReject(e);
              return Promise.reject(e);
            }
          });
        }
        var callRuntimeCallbacks = (callbacks) => {
          while (callbacks.length > 0) {
            callbacks.shift()(Module);
          }
        };
        var onPostRuns = [];
        var addOnPostRun = (cb) => onPostRuns.push(cb);
        var onPreRuns = [];
        var addOnPreRun = (cb) => onPreRuns.push(cb);
        var ptrToString = (ptr) => {
          assert2(typeof ptr === "number");
          ptr >>>= 0;
          return "0x" + ptr.toString(16).padStart(8, "0");
        };
        var warnOnce = (text) => {
          warnOnce.shown || (warnOnce.shown = {});
          if (!warnOnce.shown[text]) {
            warnOnce.shown[text] = 1;
            err(text);
          }
        };
        var UTF8Decoder = typeof TextDecoder != "undefined" ? new TextDecoder() : void 0;
        var UTF8ArrayToString = (heapOrArray, idx = 0, maxBytesToRead = NaN) => {
          var endIdx = idx + maxBytesToRead;
          var endPtr = idx;
          while (heapOrArray[endPtr] && !(endPtr >= endIdx))
            ++endPtr;
          if (endPtr - idx > 16 && heapOrArray.buffer && UTF8Decoder) {
            return UTF8Decoder.decode(heapOrArray.subarray(idx, endPtr));
          }
          var str = "";
          while (idx < endPtr) {
            var u0 = heapOrArray[idx++];
            if (!(u0 & 128)) {
              str += String.fromCharCode(u0);
              continue;
            }
            var u1 = heapOrArray[idx++] & 63;
            if ((u0 & 224) == 192) {
              str += String.fromCharCode((u0 & 31) << 6 | u1);
              continue;
            }
            var u2 = heapOrArray[idx++] & 63;
            if ((u0 & 240) == 224) {
              u0 = (u0 & 15) << 12 | u1 << 6 | u2;
            } else {
              if ((u0 & 248) != 240)
                warnOnce("Invalid UTF-8 leading byte " + ptrToString(u0) + " encountered when deserializing a UTF-8 string in wasm memory to a JS string!");
              u0 = (u0 & 7) << 18 | u1 << 12 | u2 << 6 | heapOrArray[idx++] & 63;
            }
            if (u0 < 65536) {
              str += String.fromCharCode(u0);
            } else {
              var ch = u0 - 65536;
              str += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023);
            }
          }
          return str;
        };
        var UTF8ToString = (ptr, maxBytesToRead) => {
          assert2(typeof ptr == "number", `UTF8ToString expects a number (got ${typeof ptr})`);
          return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : "";
        };
        var ___assert_fail = (condition, filename, line, func) => abort(`Assertion failed: ${UTF8ToString(condition)}, at: ` + [filename ? UTF8ToString(filename) : "unknown filename", line, func ? UTF8ToString(func) : "unknown function"]);
        var syscallGetVarargI = () => {
          assert2(SYSCALLS.varargs != void 0);
          var ret = HEAP32[+SYSCALLS.varargs >> 2];
          SYSCALLS.varargs += 4;
          return ret;
        };
        var syscallGetVarargP = syscallGetVarargI;
        var PATH = {
          isAbs: (path) => path.charAt(0) === "/",
          splitPath: (filename) => {
            var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
            return splitPathRe.exec(filename).slice(1);
          },
          normalizeArray: (parts, allowAboveRoot) => {
            var up = 0;
            for (var i2 = parts.length - 1; i2 >= 0; i2--) {
              var last = parts[i2];
              if (last === ".") {
                parts.splice(i2, 1);
              } else if (last === "..") {
                parts.splice(i2, 1);
                up++;
              } else if (up) {
                parts.splice(i2, 1);
                up--;
              }
            }
            if (allowAboveRoot) {
              for (; up; up--) {
                parts.unshift("..");
              }
            }
            return parts;
          },
          normalize: (path) => {
            var isAbsolute = PATH.isAbs(path), trailingSlash = path.slice(-1) === "/";
            path = PATH.normalizeArray(path.split("/").filter((p) => !!p), !isAbsolute).join("/");
            if (!path && !isAbsolute) {
              path = ".";
            }
            if (path && trailingSlash) {
              path += "/";
            }
            return (isAbsolute ? "/" : "") + path;
          },
          dirname: (path) => {
            var result2 = PATH.splitPath(path), root = result2[0], dir = result2[1];
            if (!root && !dir) {
              return ".";
            }
            if (dir) {
              dir = dir.slice(0, -1);
            }
            return root + dir;
          },
          basename: (path) => path && path.match(/([^\/]+|\/)\/*$/)[1],
          join: (...paths) => PATH.normalize(paths.join("/")),
          join2: (l, r) => PATH.normalize(l + "/" + r)
        };
        var initRandomFill = () => {
          return (view) => crypto.getRandomValues(view);
        };
        var randomFill = (view) => {
          (randomFill = initRandomFill())(view);
        };
        var PATH_FS = {
          resolve: (...args) => {
            var resolvedPath = "", resolvedAbsolute = false;
            for (var i2 = args.length - 1; i2 >= -1 && !resolvedAbsolute; i2--) {
              var path = i2 >= 0 ? args[i2] : FS.cwd();
              if (typeof path != "string") {
                throw new TypeError("Arguments to path.resolve must be strings");
              } else if (!path) {
                return "";
              }
              resolvedPath = path + "/" + resolvedPath;
              resolvedAbsolute = PATH.isAbs(path);
            }
            resolvedPath = PATH.normalizeArray(resolvedPath.split("/").filter((p) => !!p), !resolvedAbsolute).join("/");
            return (resolvedAbsolute ? "/" : "") + resolvedPath || ".";
          },
          relative: (from, to) => {
            from = PATH_FS.resolve(from).slice(1);
            to = PATH_FS.resolve(to).slice(1);
            function trim(arr) {
              var start = 0;
              for (; start < arr.length; start++) {
                if (arr[start] !== "")
                  break;
              }
              var end = arr.length - 1;
              for (; end >= 0; end--) {
                if (arr[end] !== "")
                  break;
              }
              if (start > end)
                return [];
              return arr.slice(start, end - start + 1);
            }
            var fromParts = trim(from.split("/"));
            var toParts = trim(to.split("/"));
            var length = Math.min(fromParts.length, toParts.length);
            var samePartsLength = length;
            for (var i2 = 0; i2 < length; i2++) {
              if (fromParts[i2] !== toParts[i2]) {
                samePartsLength = i2;
                break;
              }
            }
            var outputParts = [];
            for (var i2 = samePartsLength; i2 < fromParts.length; i2++) {
              outputParts.push("..");
            }
            outputParts = outputParts.concat(toParts.slice(samePartsLength));
            return outputParts.join("/");
          }
        };
        var FS_stdin_getChar_buffer = [];
        var lengthBytesUTF8 = (str) => {
          var len2 = 0;
          for (var i2 = 0; i2 < str.length; ++i2) {
            var c = str.charCodeAt(i2);
            if (c <= 127) {
              len2++;
            } else if (c <= 2047) {
              len2 += 2;
            } else if (c >= 55296 && c <= 57343) {
              len2 += 4;
              ++i2;
            } else {
              len2 += 3;
            }
          }
          return len2;
        };
        var stringToUTF8Array = (str, heap, outIdx, maxBytesToWrite) => {
          assert2(typeof str === "string", `stringToUTF8Array expects a string (got ${typeof str})`);
          if (!(maxBytesToWrite > 0))
            return 0;
          var startIdx = outIdx;
          var endIdx = outIdx + maxBytesToWrite - 1;
          for (var i2 = 0; i2 < str.length; ++i2) {
            var u = str.charCodeAt(i2);
            if (u >= 55296 && u <= 57343) {
              var u1 = str.charCodeAt(++i2);
              u = 65536 + ((u & 1023) << 10) | u1 & 1023;
            }
            if (u <= 127) {
              if (outIdx >= endIdx)
                break;
              heap[outIdx++] = u;
            } else if (u <= 2047) {
              if (outIdx + 1 >= endIdx)
                break;
              heap[outIdx++] = 192 | u >> 6;
              heap[outIdx++] = 128 | u & 63;
            } else if (u <= 65535) {
              if (outIdx + 2 >= endIdx)
                break;
              heap[outIdx++] = 224 | u >> 12;
              heap[outIdx++] = 128 | u >> 6 & 63;
              heap[outIdx++] = 128 | u & 63;
            } else {
              if (outIdx + 3 >= endIdx)
                break;
              if (u > 1114111)
                warnOnce("Invalid Unicode code point " + ptrToString(u) + " encountered when serializing a JS string to a UTF-8 string in wasm memory! (Valid unicode code points should be in range 0-0x10FFFF).");
              heap[outIdx++] = 240 | u >> 18;
              heap[outIdx++] = 128 | u >> 12 & 63;
              heap[outIdx++] = 128 | u >> 6 & 63;
              heap[outIdx++] = 128 | u & 63;
            }
          }
          heap[outIdx] = 0;
          return outIdx - startIdx;
        };
        var intArrayFromString = (stringy, dontAddNull, length) => {
          var len2 = lengthBytesUTF8(stringy) + 1;
          var u8array = new Array(len2);
          var numBytesWritten = stringToUTF8Array(stringy, u8array, 0, u8array.length);
          u8array.length = numBytesWritten;
          return u8array;
        };
        var FS_stdin_getChar = () => {
          if (!FS_stdin_getChar_buffer.length) {
            var result2 = null;
            if (typeof window != "undefined" && typeof window.prompt == "function") {
              result2 = window.prompt("Input: ");
              if (result2 !== null) {
                result2 += "\n";
              }
            }
            if (!result2) {
              return null;
            }
            FS_stdin_getChar_buffer = intArrayFromString(result2);
          }
          return FS_stdin_getChar_buffer.shift();
        };
        var TTY = {
          ttys: [],
          init() {
          },
          shutdown() {
          },
          register(dev, ops) {
            TTY.ttys[dev] = { input: [], output: [], ops };
            FS.registerDevice(dev, TTY.stream_ops);
          },
          stream_ops: {
            open(stream) {
              var tty = TTY.ttys[stream.node.rdev];
              if (!tty) {
                throw new FS.ErrnoError(43);
              }
              stream.tty = tty;
              stream.seekable = false;
            },
            close(stream) {
              stream.tty.ops.fsync(stream.tty);
            },
            fsync(stream) {
              stream.tty.ops.fsync(stream.tty);
            },
            read(stream, buffer2, offset, length, pos) {
              if (!stream.tty || !stream.tty.ops.get_char) {
                throw new FS.ErrnoError(60);
              }
              var bytesRead = 0;
              for (var i2 = 0; i2 < length; i2++) {
                var result2;
                try {
                  result2 = stream.tty.ops.get_char(stream.tty);
                } catch (e) {
                  throw new FS.ErrnoError(29);
                }
                if (result2 === void 0 && bytesRead === 0) {
                  throw new FS.ErrnoError(6);
                }
                if (result2 === null || result2 === void 0)
                  break;
                bytesRead++;
                buffer2[offset + i2] = result2;
              }
              if (bytesRead) {
                stream.node.atime = Date.now();
              }
              return bytesRead;
            },
            write(stream, buffer2, offset, length, pos) {
              if (!stream.tty || !stream.tty.ops.put_char) {
                throw new FS.ErrnoError(60);
              }
              try {
                for (var i2 = 0; i2 < length; i2++) {
                  stream.tty.ops.put_char(stream.tty, buffer2[offset + i2]);
                }
              } catch (e) {
                throw new FS.ErrnoError(29);
              }
              if (length) {
                stream.node.mtime = stream.node.ctime = Date.now();
              }
              return i2;
            }
          },
          default_tty_ops: {
            get_char(tty) {
              return FS_stdin_getChar();
            },
            put_char(tty, val) {
              if (val === null || val === 10) {
                out(UTF8ArrayToString(tty.output));
                tty.output = [];
              } else {
                if (val != 0)
                  tty.output.push(val);
              }
            },
            fsync(tty) {
              var _a3;
              if (((_a3 = tty.output) == null ? void 0 : _a3.length) > 0) {
                out(UTF8ArrayToString(tty.output));
                tty.output = [];
              }
            },
            ioctl_tcgets(tty) {
              return {
                c_iflag: 25856,
                c_oflag: 5,
                c_cflag: 191,
                c_lflag: 35387,
                c_cc: [
                  3,
                  28,
                  127,
                  21,
                  4,
                  0,
                  1,
                  0,
                  17,
                  19,
                  26,
                  0,
                  18,
                  15,
                  23,
                  22,
                  0,
                  0,
                  0,
                  0,
                  0,
                  0,
                  0,
                  0,
                  0,
                  0,
                  0,
                  0,
                  0,
                  0,
                  0,
                  0
                ]
              };
            },
            ioctl_tcsets(tty, optional_actions, data) {
              return 0;
            },
            ioctl_tiocgwinsz(tty) {
              return [24, 80];
            }
          },
          default_tty1_ops: {
            put_char(tty, val) {
              if (val === null || val === 10) {
                err(UTF8ArrayToString(tty.output));
                tty.output = [];
              } else {
                if (val != 0)
                  tty.output.push(val);
              }
            },
            fsync(tty) {
              var _a3;
              if (((_a3 = tty.output) == null ? void 0 : _a3.length) > 0) {
                err(UTF8ArrayToString(tty.output));
                tty.output = [];
              }
            }
          }
        };
        var mmapAlloc = (size) => {
          abort("internal error: mmapAlloc called but `emscripten_builtin_memalign` native symbol not exported");
        };
        var MEMFS = {
          ops_table: null,
          mount(mount) {
            return MEMFS.createNode(null, "/", 16895, 0);
          },
          createNode(parent, name2, mode, dev) {
            if (FS.isBlkdev(mode) || FS.isFIFO(mode)) {
              throw new FS.ErrnoError(63);
            }
            MEMFS.ops_table || (MEMFS.ops_table = {
              dir: {
                node: {
                  getattr: MEMFS.node_ops.getattr,
                  setattr: MEMFS.node_ops.setattr,
                  lookup: MEMFS.node_ops.lookup,
                  mknod: MEMFS.node_ops.mknod,
                  rename: MEMFS.node_ops.rename,
                  unlink: MEMFS.node_ops.unlink,
                  rmdir: MEMFS.node_ops.rmdir,
                  readdir: MEMFS.node_ops.readdir,
                  symlink: MEMFS.node_ops.symlink
                },
                stream: {
                  llseek: MEMFS.stream_ops.llseek
                }
              },
              file: {
                node: {
                  getattr: MEMFS.node_ops.getattr,
                  setattr: MEMFS.node_ops.setattr
                },
                stream: {
                  llseek: MEMFS.stream_ops.llseek,
                  read: MEMFS.stream_ops.read,
                  write: MEMFS.stream_ops.write,
                  mmap: MEMFS.stream_ops.mmap,
                  msync: MEMFS.stream_ops.msync
                }
              },
              link: {
                node: {
                  getattr: MEMFS.node_ops.getattr,
                  setattr: MEMFS.node_ops.setattr,
                  readlink: MEMFS.node_ops.readlink
                },
                stream: {}
              },
              chrdev: {
                node: {
                  getattr: MEMFS.node_ops.getattr,
                  setattr: MEMFS.node_ops.setattr
                },
                stream: FS.chrdev_stream_ops
              }
            });
            var node = FS.createNode(parent, name2, mode, dev);
            if (FS.isDir(node.mode)) {
              node.node_ops = MEMFS.ops_table.dir.node;
              node.stream_ops = MEMFS.ops_table.dir.stream;
              node.contents = {};
            } else if (FS.isFile(node.mode)) {
              node.node_ops = MEMFS.ops_table.file.node;
              node.stream_ops = MEMFS.ops_table.file.stream;
              node.usedBytes = 0;
              node.contents = null;
            } else if (FS.isLink(node.mode)) {
              node.node_ops = MEMFS.ops_table.link.node;
              node.stream_ops = MEMFS.ops_table.link.stream;
            } else if (FS.isChrdev(node.mode)) {
              node.node_ops = MEMFS.ops_table.chrdev.node;
              node.stream_ops = MEMFS.ops_table.chrdev.stream;
            }
            node.atime = node.mtime = node.ctime = Date.now();
            if (parent) {
              parent.contents[name2] = node;
              parent.atime = parent.mtime = parent.ctime = node.atime;
            }
            return node;
          },
          getFileDataAsTypedArray(node) {
            if (!node.contents)
              return new Uint8Array(0);
            if (node.contents.subarray)
              return node.contents.subarray(0, node.usedBytes);
            return new Uint8Array(node.contents);
          },
          expandFileStorage(node, newCapacity) {
            var prevCapacity = node.contents ? node.contents.length : 0;
            if (prevCapacity >= newCapacity)
              return;
            var CAPACITY_DOUBLING_MAX = 1024 * 1024;
            newCapacity = Math.max(newCapacity, prevCapacity * (prevCapacity < CAPACITY_DOUBLING_MAX ? 2 : 1.125) >>> 0);
            if (prevCapacity != 0)
              newCapacity = Math.max(newCapacity, 256);
            var oldContents = node.contents;
            node.contents = new Uint8Array(newCapacity);
            if (node.usedBytes > 0)
              node.contents.set(oldContents.subarray(0, node.usedBytes), 0);
          },
          resizeFileStorage(node, newSize) {
            if (node.usedBytes == newSize)
              return;
            if (newSize == 0) {
              node.contents = null;
              node.usedBytes = 0;
            } else {
              var oldContents = node.contents;
              node.contents = new Uint8Array(newSize);
              if (oldContents) {
                node.contents.set(oldContents.subarray(0, Math.min(newSize, node.usedBytes)));
              }
              node.usedBytes = newSize;
            }
          },
          node_ops: {
            getattr(node) {
              var attr = {};
              attr.dev = FS.isChrdev(node.mode) ? node.id : 1;
              attr.ino = node.id;
              attr.mode = node.mode;
              attr.nlink = 1;
              attr.uid = 0;
              attr.gid = 0;
              attr.rdev = node.rdev;
              if (FS.isDir(node.mode)) {
                attr.size = 4096;
              } else if (FS.isFile(node.mode)) {
                attr.size = node.usedBytes;
              } else if (FS.isLink(node.mode)) {
                attr.size = node.link.length;
              } else {
                attr.size = 0;
              }
              attr.atime = new Date(node.atime);
              attr.mtime = new Date(node.mtime);
              attr.ctime = new Date(node.ctime);
              attr.blksize = 4096;
              attr.blocks = Math.ceil(attr.size / attr.blksize);
              return attr;
            },
            setattr(node, attr) {
              for (const key of ["mode", "atime", "mtime", "ctime"]) {
                if (attr[key] != null) {
                  node[key] = attr[key];
                }
              }
              if (attr.size !== void 0) {
                MEMFS.resizeFileStorage(node, attr.size);
              }
            },
            lookup(parent, name2) {
              throw new FS.ErrnoError(44);
            },
            mknod(parent, name2, mode, dev) {
              return MEMFS.createNode(parent, name2, mode, dev);
            },
            rename(old_node, new_dir, new_name) {
              var new_node;
              try {
                new_node = FS.lookupNode(new_dir, new_name);
              } catch (e) {
              }
              if (new_node) {
                if (FS.isDir(old_node.mode)) {
                  for (var i2 in new_node.contents) {
                    throw new FS.ErrnoError(55);
                  }
                }
                FS.hashRemoveNode(new_node);
              }
              delete old_node.parent.contents[old_node.name];
              new_dir.contents[new_name] = old_node;
              old_node.name = new_name;
              new_dir.ctime = new_dir.mtime = old_node.parent.ctime = old_node.parent.mtime = Date.now();
            },
            unlink(parent, name2) {
              delete parent.contents[name2];
              parent.ctime = parent.mtime = Date.now();
            },
            rmdir(parent, name2) {
              var node = FS.lookupNode(parent, name2);
              for (var i2 in node.contents) {
                throw new FS.ErrnoError(55);
              }
              delete parent.contents[name2];
              parent.ctime = parent.mtime = Date.now();
            },
            readdir(node) {
              return [".", "..", ...Object.keys(node.contents)];
            },
            symlink(parent, newname, oldpath) {
              var node = MEMFS.createNode(parent, newname, 511 | 40960, 0);
              node.link = oldpath;
              return node;
            },
            readlink(node) {
              if (!FS.isLink(node.mode)) {
                throw new FS.ErrnoError(28);
              }
              return node.link;
            }
          },
          stream_ops: {
            read(stream, buffer2, offset, length, position) {
              var contents = stream.node.contents;
              if (position >= stream.node.usedBytes)
                return 0;
              var size = Math.min(stream.node.usedBytes - position, length);
              assert2(size >= 0);
              if (size > 8 && contents.subarray) {
                buffer2.set(contents.subarray(position, position + size), offset);
              } else {
                for (var i2 = 0; i2 < size; i2++)
                  buffer2[offset + i2] = contents[position + i2];
              }
              return size;
            },
            write(stream, buffer2, offset, length, position, canOwn) {
              assert2(!(buffer2 instanceof ArrayBuffer));
              if (buffer2.buffer === HEAP8.buffer) {
                canOwn = false;
              }
              if (!length)
                return 0;
              var node = stream.node;
              node.mtime = node.ctime = Date.now();
              if (buffer2.subarray && (!node.contents || node.contents.subarray)) {
                if (canOwn) {
                  assert2(position === 0, "canOwn must imply no weird position inside the file");
                  node.contents = buffer2.subarray(offset, offset + length);
                  node.usedBytes = length;
                  return length;
                } else if (node.usedBytes === 0 && position === 0) {
                  node.contents = buffer2.slice(offset, offset + length);
                  node.usedBytes = length;
                  return length;
                } else if (position + length <= node.usedBytes) {
                  node.contents.set(buffer2.subarray(offset, offset + length), position);
                  return length;
                }
              }
              MEMFS.expandFileStorage(node, position + length);
              if (node.contents.subarray && buffer2.subarray) {
                node.contents.set(buffer2.subarray(offset, offset + length), position);
              } else {
                for (var i2 = 0; i2 < length; i2++) {
                  node.contents[position + i2] = buffer2[offset + i2];
                }
              }
              node.usedBytes = Math.max(node.usedBytes, position + length);
              return length;
            },
            llseek(stream, offset, whence) {
              var position = offset;
              if (whence === 1) {
                position += stream.position;
              } else if (whence === 2) {
                if (FS.isFile(stream.node.mode)) {
                  position += stream.node.usedBytes;
                }
              }
              if (position < 0) {
                throw new FS.ErrnoError(28);
              }
              return position;
            },
            mmap(stream, length, position, prot, flags) {
              if (!FS.isFile(stream.node.mode)) {
                throw new FS.ErrnoError(43);
              }
              var ptr;
              var allocated;
              var contents = stream.node.contents;
              if (!(flags & 2) && contents && contents.buffer === HEAP8.buffer) {
                allocated = false;
                ptr = contents.byteOffset;
              } else {
                allocated = true;
                ptr = mmapAlloc();
                if (!ptr) {
                  throw new FS.ErrnoError(48);
                }
                if (contents) {
                  if (position > 0 || position + length < contents.length) {
                    if (contents.subarray) {
                      contents = contents.subarray(position, position + length);
                    } else {
                      contents = Array.prototype.slice.call(contents, position, position + length);
                    }
                  }
                  HEAP8.set(contents, ptr);
                }
              }
              return { ptr, allocated };
            },
            msync(stream, buffer2, offset, length, mmapFlags) {
              MEMFS.stream_ops.write(stream, buffer2, 0, length, offset, false);
              return 0;
            }
          }
        };
        var asyncLoad = (url2) => __async(null, null, function* () {
          var arrayBuffer = yield readAsync(url2);
          assert2(arrayBuffer, `Loading data file "${url2}" failed (no arrayBuffer).`);
          return new Uint8Array(arrayBuffer);
        });
        var FS_createDataFile = (...args) => FS.createDataFile(...args);
        var preloadPlugins = [];
        var FS_handledByPreloadPlugin = (byteArray, fullname, finish, onerror) => {
          if (typeof Browser != "undefined")
            Browser.init();
          var handled = false;
          preloadPlugins.forEach((plugin) => {
            if (handled)
              return;
            if (plugin["canHandle"](fullname)) {
              plugin["handle"](byteArray, fullname, finish, onerror);
              handled = true;
            }
          });
          return handled;
        };
        var FS_createPreloadedFile = (parent, name2, url2, canRead, canWrite, onload, onerror, dontCreateFile, canOwn, preFinish) => {
          var fullname = name2 ? PATH_FS.resolve(PATH.join2(parent, name2)) : parent;
          var dep = getUniqueRunDependency(`cp ${fullname}`);
          function processData(byteArray) {
            function finish(byteArray2) {
              preFinish == null ? void 0 : preFinish();
              if (!dontCreateFile) {
                FS_createDataFile(parent, name2, byteArray2, canRead, canWrite, canOwn);
              }
              onload == null ? void 0 : onload();
              removeRunDependency(dep);
            }
            if (FS_handledByPreloadPlugin(byteArray, fullname, finish, () => {
              onerror == null ? void 0 : onerror();
              removeRunDependency(dep);
            })) {
              return;
            }
            finish(byteArray);
          }
          addRunDependency(dep);
          if (typeof url2 == "string") {
            asyncLoad(url2).then(processData, onerror);
          } else {
            processData(url2);
          }
        };
        var FS_modeStringToFlags = (str) => {
          var flagModes = {
            "r": 0,
            "r+": 2,
            "w": 512 | 64 | 1,
            "w+": 512 | 64 | 2,
            "a": 1024 | 64 | 1,
            "a+": 1024 | 64 | 2
          };
          var flags = flagModes[str];
          if (typeof flags == "undefined") {
            throw new Error(`Unknown file open mode: ${str}`);
          }
          return flags;
        };
        var FS_getMode = (canRead, canWrite) => {
          var mode = 0;
          if (canRead)
            mode |= 292 | 73;
          if (canWrite)
            mode |= 146;
          return mode;
        };
        var IDBFS = {
          dbs: {},
          indexedDB: () => {
            if (typeof indexedDB != "undefined")
              return indexedDB;
            var ret = null;
            if (typeof window == "object")
              ret = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
            assert2(ret, "IDBFS used, but indexedDB not supported");
            return ret;
          },
          DB_VERSION: 21,
          DB_STORE_NAME: "FILE_DATA",
          queuePersist: (mount) => {
            function onPersistComplete() {
              if (mount.idbPersistState === "again")
                startPersist();
              else
                mount.idbPersistState = 0;
            }
            function startPersist() {
              mount.idbPersistState = "idb";
              IDBFS.syncfs(
                mount,
                /*populate:*/
                false,
                onPersistComplete
              );
            }
            if (!mount.idbPersistState) {
              mount.idbPersistState = setTimeout(startPersist, 0);
            } else if (mount.idbPersistState === "idb") {
              mount.idbPersistState = "again";
            }
          },
          mount: (mount) => {
            var _a3;
            var mnt = MEMFS.mount(mount);
            if ((_a3 = mount == null ? void 0 : mount.opts) == null ? void 0 : _a3.autoPersist) {
              mnt.idbPersistState = 0;
              var memfs_node_ops = mnt.node_ops;
              mnt.node_ops = __spreadValues({}, mnt.node_ops);
              mnt.node_ops.mknod = (parent, name2, mode, dev) => {
                var node = memfs_node_ops.mknod(parent, name2, mode, dev);
                node.node_ops = mnt.node_ops;
                node.idbfs_mount = mnt.mount;
                node.memfs_stream_ops = node.stream_ops;
                node.stream_ops = __spreadValues({}, node.stream_ops);
                node.stream_ops.write = (stream, buffer2, offset, length, position, canOwn) => {
                  stream.node.isModified = true;
                  return node.memfs_stream_ops.write(stream, buffer2, offset, length, position, canOwn);
                };
                node.stream_ops.close = (stream) => {
                  var n = stream.node;
                  if (n.isModified) {
                    IDBFS.queuePersist(n.idbfs_mount);
                    n.isModified = false;
                  }
                  if (n.memfs_stream_ops.close)
                    return n.memfs_stream_ops.close(stream);
                };
                return node;
              };
              mnt.node_ops.mkdir = (...args) => (IDBFS.queuePersist(mnt.mount), memfs_node_ops.mkdir(...args));
              mnt.node_ops.rmdir = (...args) => (IDBFS.queuePersist(mnt.mount), memfs_node_ops.rmdir(...args));
              mnt.node_ops.symlink = (...args) => (IDBFS.queuePersist(mnt.mount), memfs_node_ops.symlink(...args));
              mnt.node_ops.unlink = (...args) => (IDBFS.queuePersist(mnt.mount), memfs_node_ops.unlink(...args));
              mnt.node_ops.rename = (...args) => (IDBFS.queuePersist(mnt.mount), memfs_node_ops.rename(...args));
            }
            return mnt;
          },
          syncfs: (mount, populate, callback) => {
            IDBFS.getLocalSet(mount, (err2, local) => {
              if (err2)
                return callback(err2);
              IDBFS.getRemoteSet(mount, (err3, remote) => {
                if (err3)
                  return callback(err3);
                var src = populate ? remote : local;
                var dst = populate ? local : remote;
                IDBFS.reconcile(src, dst, callback);
              });
            });
          },
          quit: () => {
            Object.values(IDBFS.dbs).forEach((value) => value.close());
            IDBFS.dbs = {};
          },
          getDB: (name2, callback) => {
            var db = IDBFS.dbs[name2];
            if (db) {
              return callback(null, db);
            }
            var req;
            try {
              req = IDBFS.indexedDB().open(name2, IDBFS.DB_VERSION);
            } catch (e) {
              return callback(e);
            }
            if (!req) {
              return callback("Unable to connect to IndexedDB");
            }
            req.onupgradeneeded = (e) => {
              var db2 = (
                /** @type {IDBDatabase} */
                e.target.result
              );
              var transaction = e.target.transaction;
              var fileStore;
              if (db2.objectStoreNames.contains(IDBFS.DB_STORE_NAME)) {
                fileStore = transaction.objectStore(IDBFS.DB_STORE_NAME);
              } else {
                fileStore = db2.createObjectStore(IDBFS.DB_STORE_NAME);
              }
              if (!fileStore.indexNames.contains("timestamp")) {
                fileStore.createIndex("timestamp", "timestamp", { unique: false });
              }
            };
            req.onsuccess = () => {
              db = /** @type {IDBDatabase} */
              req.result;
              IDBFS.dbs[name2] = db;
              callback(null, db);
            };
            req.onerror = (e) => {
              callback(e.target.error);
              e.preventDefault();
            };
          },
          getLocalSet: (mount, callback) => {
            var entries = {};
            function isRealDir(p) {
              return p !== "." && p !== "..";
            }
            function toAbsolute(root) {
              return (p) => PATH.join2(root, p);
            }
            var check2 = FS.readdir(mount.mountpoint).filter(isRealDir).map(toAbsolute(mount.mountpoint));
            while (check2.length) {
              var path = check2.pop();
              var stat;
              try {
                stat = FS.stat(path);
              } catch (e) {
                return callback(e);
              }
              if (FS.isDir(stat.mode)) {
                check2.push(...FS.readdir(path).filter(isRealDir).map(toAbsolute(path)));
              }
              entries[path] = { "timestamp": stat.mtime };
            }
            return callback(null, { type: "local", entries });
          },
          getRemoteSet: (mount, callback) => {
            var entries = {};
            IDBFS.getDB(mount.mountpoint, (err2, db) => {
              if (err2)
                return callback(err2);
              try {
                var transaction = db.transaction([IDBFS.DB_STORE_NAME], "readonly");
                transaction.onerror = (e) => {
                  callback(e.target.error);
                  e.preventDefault();
                };
                var store = transaction.objectStore(IDBFS.DB_STORE_NAME);
                var index2 = store.index("timestamp");
                index2.openKeyCursor().onsuccess = (event) => {
                  var cursor = event.target.result;
                  if (!cursor) {
                    return callback(null, { type: "remote", db, entries });
                  }
                  entries[cursor.primaryKey] = { "timestamp": cursor.key };
                  cursor.continue();
                };
              } catch (e) {
                return callback(e);
              }
            });
          },
          loadLocalEntry: (path, callback) => {
            var stat, node;
            try {
              var lookup2 = FS.lookupPath(path);
              node = lookup2.node;
              stat = FS.stat(path);
            } catch (e) {
              return callback(e);
            }
            if (FS.isDir(stat.mode)) {
              return callback(null, { "timestamp": stat.mtime, "mode": stat.mode });
            } else if (FS.isFile(stat.mode)) {
              node.contents = MEMFS.getFileDataAsTypedArray(node);
              return callback(null, { "timestamp": stat.mtime, "mode": stat.mode, "contents": node.contents });
            } else {
              return callback(new Error("node type not supported"));
            }
          },
          storeLocalEntry: (path, entry, callback) => {
            try {
              if (FS.isDir(entry["mode"])) {
                FS.mkdirTree(path, entry["mode"]);
              } else if (FS.isFile(entry["mode"])) {
                FS.writeFile(path, entry["contents"], { canOwn: true });
              } else {
                return callback(new Error("node type not supported"));
              }
              FS.chmod(path, entry["mode"]);
              FS.utime(path, entry["timestamp"], entry["timestamp"]);
            } catch (e) {
              return callback(e);
            }
            callback(null);
          },
          removeLocalEntry: (path, callback) => {
            try {
              var stat = FS.stat(path);
              if (FS.isDir(stat.mode)) {
                FS.rmdir(path);
              } else if (FS.isFile(stat.mode)) {
                FS.unlink(path);
              }
            } catch (e) {
              return callback(e);
            }
            callback(null);
          },
          loadRemoteEntry: (store, path, callback) => {
            var req = store.get(path);
            req.onsuccess = (event) => callback(null, event.target.result);
            req.onerror = (e) => {
              callback(e.target.error);
              e.preventDefault();
            };
          },
          storeRemoteEntry: (store, path, entry, callback) => {
            try {
              var req = store.put(entry, path);
            } catch (e) {
              callback(e);
              return;
            }
            req.onsuccess = (event) => callback();
            req.onerror = (e) => {
              callback(e.target.error);
              e.preventDefault();
            };
          },
          removeRemoteEntry: (store, path, callback) => {
            var req = store.delete(path);
            req.onsuccess = (event) => callback();
            req.onerror = (e) => {
              callback(e.target.error);
              e.preventDefault();
            };
          },
          reconcile: (src, dst, callback) => {
            var total = 0;
            var create2 = [];
            Object.keys(src.entries).forEach((key) => {
              var e = src.entries[key];
              var e2 = dst.entries[key];
              if (!e2 || e["timestamp"].getTime() != e2["timestamp"].getTime()) {
                create2.push(key);
                total++;
              }
            });
            var remove = [];
            Object.keys(dst.entries).forEach((key) => {
              if (!src.entries[key]) {
                remove.push(key);
                total++;
              }
            });
            if (!total) {
              return callback(null);
            }
            var errored = false;
            var db = src.type === "remote" ? src.db : dst.db;
            var transaction = db.transaction([IDBFS.DB_STORE_NAME], "readwrite");
            var store = transaction.objectStore(IDBFS.DB_STORE_NAME);
            function done(err2) {
              if (err2 && !errored) {
                errored = true;
                return callback(err2);
              }
            }
            transaction.onerror = transaction.onabort = (e) => {
              done(e.target.error);
              e.preventDefault();
            };
            transaction.oncomplete = (e) => {
              if (!errored) {
                callback(null);
              }
            };
            create2.sort().forEach((path) => {
              if (dst.type === "local") {
                IDBFS.loadRemoteEntry(store, path, (err2, entry) => {
                  if (err2)
                    return done(err2);
                  IDBFS.storeLocalEntry(path, entry, done);
                });
              } else {
                IDBFS.loadLocalEntry(path, (err2, entry) => {
                  if (err2)
                    return done(err2);
                  IDBFS.storeRemoteEntry(store, path, entry, done);
                });
              }
            });
            remove.sort().reverse().forEach((path) => {
              if (dst.type === "local") {
                IDBFS.removeLocalEntry(path, done);
              } else {
                IDBFS.removeRemoteEntry(store, path, done);
              }
            });
          }
        };
        var strError = (errno) => UTF8ToString(_strerror(errno));
        var ERRNO_CODES = {
          "EPERM": 63,
          "ENOENT": 44,
          "ESRCH": 71,
          "EINTR": 27,
          "EIO": 29,
          "ENXIO": 60,
          "E2BIG": 1,
          "ENOEXEC": 45,
          "EBADF": 8,
          "ECHILD": 12,
          "EAGAIN": 6,
          "EWOULDBLOCK": 6,
          "ENOMEM": 48,
          "EACCES": 2,
          "EFAULT": 21,
          "ENOTBLK": 105,
          "EBUSY": 10,
          "EEXIST": 20,
          "EXDEV": 75,
          "ENODEV": 43,
          "ENOTDIR": 54,
          "EISDIR": 31,
          "EINVAL": 28,
          "ENFILE": 41,
          "EMFILE": 33,
          "ENOTTY": 59,
          "ETXTBSY": 74,
          "EFBIG": 22,
          "ENOSPC": 51,
          "ESPIPE": 70,
          "EROFS": 69,
          "EMLINK": 34,
          "EPIPE": 64,
          "EDOM": 18,
          "ERANGE": 68,
          "ENOMSG": 49,
          "EIDRM": 24,
          "ECHRNG": 106,
          "EL2NSYNC": 156,
          "EL3HLT": 107,
          "EL3RST": 108,
          "ELNRNG": 109,
          "EUNATCH": 110,
          "ENOCSI": 111,
          "EL2HLT": 112,
          "EDEADLK": 16,
          "ENOLCK": 46,
          "EBADE": 113,
          "EBADR": 114,
          "EXFULL": 115,
          "ENOANO": 104,
          "EBADRQC": 103,
          "EBADSLT": 102,
          "EDEADLOCK": 16,
          "EBFONT": 101,
          "ENOSTR": 100,
          "ENODATA": 116,
          "ETIME": 117,
          "ENOSR": 118,
          "ENONET": 119,
          "ENOPKG": 120,
          "EREMOTE": 121,
          "ENOLINK": 47,
          "EADV": 122,
          "ESRMNT": 123,
          "ECOMM": 124,
          "EPROTO": 65,
          "EMULTIHOP": 36,
          "EDOTDOT": 125,
          "EBADMSG": 9,
          "ENOTUNIQ": 126,
          "EBADFD": 127,
          "EREMCHG": 128,
          "ELIBACC": 129,
          "ELIBBAD": 130,
          "ELIBSCN": 131,
          "ELIBMAX": 132,
          "ELIBEXEC": 133,
          "ENOSYS": 52,
          "ENOTEMPTY": 55,
          "ENAMETOOLONG": 37,
          "ELOOP": 32,
          "EOPNOTSUPP": 138,
          "EPFNOSUPPORT": 139,
          "ECONNRESET": 15,
          "ENOBUFS": 42,
          "EAFNOSUPPORT": 5,
          "EPROTOTYPE": 67,
          "ENOTSOCK": 57,
          "ENOPROTOOPT": 50,
          "ESHUTDOWN": 140,
          "ECONNREFUSED": 14,
          "EADDRINUSE": 3,
          "ECONNABORTED": 13,
          "ENETUNREACH": 40,
          "ENETDOWN": 38,
          "ETIMEDOUT": 73,
          "EHOSTDOWN": 142,
          "EHOSTUNREACH": 23,
          "EINPROGRESS": 26,
          "EALREADY": 7,
          "EDESTADDRREQ": 17,
          "EMSGSIZE": 35,
          "EPROTONOSUPPORT": 66,
          "ESOCKTNOSUPPORT": 137,
          "EADDRNOTAVAIL": 4,
          "ENETRESET": 39,
          "EISCONN": 30,
          "ENOTCONN": 53,
          "ETOOMANYREFS": 141,
          "EUSERS": 136,
          "EDQUOT": 19,
          "ESTALE": 72,
          "ENOTSUP": 138,
          "ENOMEDIUM": 148,
          "EILSEQ": 25,
          "EOVERFLOW": 61,
          "ECANCELED": 11,
          "ENOTRECOVERABLE": 56,
          "EOWNERDEAD": 62,
          "ESTRPIPE": 135
        };
        var FS = {
          root: null,
          mounts: [],
          devices: {},
          streams: [],
          nextInode: 1,
          nameTable: null,
          currentPath: "/",
          initialized: false,
          ignorePermissions: true,
          filesystems: null,
          syncFSRequests: 0,
          readFiles: {},
          ErrnoError: class extends Error {
            // We set the `name` property to be able to identify `FS.ErrnoError`
            // - the `name` is a standard ECMA-262 property of error objects. Kind of good to have it anyway.
            // - when using PROXYFS, an error can come from an underlying FS
            // as different FS objects have their own FS.ErrnoError each,
            // the test `err instanceof FS.ErrnoError` won't detect an error coming from another filesystem, causing bugs.
            // we'll use the reliable test `err.name == "ErrnoError"` instead
            constructor(errno) {
              super(runtimeInitialized ? strError(errno) : "");
              __publicField(this, "name", "ErrnoError");
              this.errno = errno;
              for (var key in ERRNO_CODES) {
                if (ERRNO_CODES[key] === errno) {
                  this.code = key;
                  break;
                }
              }
            }
          },
          FSStream: class {
            constructor() {
              __publicField(this, "shared", {});
            }
            get object() {
              return this.node;
            }
            set object(val) {
              this.node = val;
            }
            get isRead() {
              return (this.flags & 2097155) !== 1;
            }
            get isWrite() {
              return (this.flags & 2097155) !== 0;
            }
            get isAppend() {
              return this.flags & 1024;
            }
            get flags() {
              return this.shared.flags;
            }
            set flags(val) {
              this.shared.flags = val;
            }
            get position() {
              return this.shared.position;
            }
            set position(val) {
              this.shared.position = val;
            }
          },
          FSNode: class {
            constructor(parent, name2, mode, rdev) {
              __publicField(this, "node_ops", {});
              __publicField(this, "stream_ops", {});
              __publicField(this, "readMode", 292 | 73);
              __publicField(this, "writeMode", 146);
              __publicField(this, "mounted", null);
              if (!parent) {
                parent = this;
              }
              this.parent = parent;
              this.mount = parent.mount;
              this.id = FS.nextInode++;
              this.name = name2;
              this.mode = mode;
              this.rdev = rdev;
              this.atime = this.mtime = this.ctime = Date.now();
            }
            get read() {
              return (this.mode & this.readMode) === this.readMode;
            }
            set read(val) {
              val ? this.mode |= this.readMode : this.mode &= ~this.readMode;
            }
            get write() {
              return (this.mode & this.writeMode) === this.writeMode;
            }
            set write(val) {
              val ? this.mode |= this.writeMode : this.mode &= ~this.writeMode;
            }
            get isFolder() {
              return FS.isDir(this.mode);
            }
            get isDevice() {
              return FS.isChrdev(this.mode);
            }
          },
          lookupPath(path, opts = {}) {
            var _a3;
            if (!path) {
              throw new FS.ErrnoError(44);
            }
            (_a3 = opts.follow_mount) != null ? _a3 : opts.follow_mount = true;
            if (!PATH.isAbs(path)) {
              path = FS.cwd() + "/" + path;
            }
            linkloop:
              for (var nlinks = 0; nlinks < 40; nlinks++) {
                var parts = path.split("/").filter((p) => !!p);
                var current = FS.root;
                var current_path = "/";
                for (var i2 = 0; i2 < parts.length; i2++) {
                  var islast = i2 === parts.length - 1;
                  if (islast && opts.parent) {
                    break;
                  }
                  if (parts[i2] === ".") {
                    continue;
                  }
                  if (parts[i2] === "..") {
                    current_path = PATH.dirname(current_path);
                    if (FS.isRoot(current)) {
                      path = current_path + "/" + parts.slice(i2 + 1).join("/");
                      continue linkloop;
                    } else {
                      current = current.parent;
                    }
                    continue;
                  }
                  current_path = PATH.join2(current_path, parts[i2]);
                  try {
                    current = FS.lookupNode(current, parts[i2]);
                  } catch (e) {
                    if ((e == null ? void 0 : e.errno) === 44 && islast && opts.noent_okay) {
                      return { path: current_path };
                    }
                    throw e;
                  }
                  if (FS.isMountpoint(current) && (!islast || opts.follow_mount)) {
                    current = current.mounted.root;
                  }
                  if (FS.isLink(current.mode) && (!islast || opts.follow)) {
                    if (!current.node_ops.readlink) {
                      throw new FS.ErrnoError(52);
                    }
                    var link = current.node_ops.readlink(current);
                    if (!PATH.isAbs(link)) {
                      link = PATH.dirname(current_path) + "/" + link;
                    }
                    path = link + "/" + parts.slice(i2 + 1).join("/");
                    continue linkloop;
                  }
                }
                return { path: current_path, node: current };
              }
            throw new FS.ErrnoError(32);
          },
          getPath(node) {
            var path;
            while (true) {
              if (FS.isRoot(node)) {
                var mount = node.mount.mountpoint;
                if (!path)
                  return mount;
                return mount[mount.length - 1] !== "/" ? `${mount}/${path}` : mount + path;
              }
              path = path ? `${node.name}/${path}` : node.name;
              node = node.parent;
            }
          },
          hashName(parentid, name2) {
            var hash2 = 0;
            for (var i2 = 0; i2 < name2.length; i2++) {
              hash2 = (hash2 << 5) - hash2 + name2.charCodeAt(i2) | 0;
            }
            return (parentid + hash2 >>> 0) % FS.nameTable.length;
          },
          hashAddNode(node) {
            var hash2 = FS.hashName(node.parent.id, node.name);
            node.name_next = FS.nameTable[hash2];
            FS.nameTable[hash2] = node;
          },
          hashRemoveNode(node) {
            var hash2 = FS.hashName(node.parent.id, node.name);
            if (FS.nameTable[hash2] === node) {
              FS.nameTable[hash2] = node.name_next;
            } else {
              var current = FS.nameTable[hash2];
              while (current) {
                if (current.name_next === node) {
                  current.name_next = node.name_next;
                  break;
                }
                current = current.name_next;
              }
            }
          },
          lookupNode(parent, name2) {
            var errCode = FS.mayLookup(parent);
            if (errCode) {
              throw new FS.ErrnoError(errCode);
            }
            var hash2 = FS.hashName(parent.id, name2);
            for (var node = FS.nameTable[hash2]; node; node = node.name_next) {
              var nodeName = node.name;
              if (node.parent.id === parent.id && nodeName === name2) {
                return node;
              }
            }
            return FS.lookup(parent, name2);
          },
          createNode(parent, name2, mode, rdev) {
            assert2(typeof parent == "object");
            var node = new FS.FSNode(parent, name2, mode, rdev);
            FS.hashAddNode(node);
            return node;
          },
          destroyNode(node) {
            FS.hashRemoveNode(node);
          },
          isRoot(node) {
            return node === node.parent;
          },
          isMountpoint(node) {
            return !!node.mounted;
          },
          isFile(mode) {
            return (mode & 61440) === 32768;
          },
          isDir(mode) {
            return (mode & 61440) === 16384;
          },
          isLink(mode) {
            return (mode & 61440) === 40960;
          },
          isChrdev(mode) {
            return (mode & 61440) === 8192;
          },
          isBlkdev(mode) {
            return (mode & 61440) === 24576;
          },
          isFIFO(mode) {
            return (mode & 61440) === 4096;
          },
          isSocket(mode) {
            return (mode & 49152) === 49152;
          },
          flagsToPermissionString(flag) {
            var perms = ["r", "w", "rw"][flag & 3];
            if (flag & 512) {
              perms += "w";
            }
            return perms;
          },
          nodePermissions(node, perms) {
            if (FS.ignorePermissions) {
              return 0;
            }
            if (perms.includes("r") && !(node.mode & 292)) {
              return 2;
            } else if (perms.includes("w") && !(node.mode & 146)) {
              return 2;
            } else if (perms.includes("x") && !(node.mode & 73)) {
              return 2;
            }
            return 0;
          },
          mayLookup(dir) {
            if (!FS.isDir(dir.mode))
              return 54;
            var errCode = FS.nodePermissions(dir, "x");
            if (errCode)
              return errCode;
            if (!dir.node_ops.lookup)
              return 2;
            return 0;
          },
          mayCreate(dir, name2) {
            if (!FS.isDir(dir.mode)) {
              return 54;
            }
            try {
              var node = FS.lookupNode(dir, name2);
              return 20;
            } catch (e) {
            }
            return FS.nodePermissions(dir, "wx");
          },
          mayDelete(dir, name2, isdir) {
            var node;
            try {
              node = FS.lookupNode(dir, name2);
            } catch (e) {
              return e.errno;
            }
            var errCode = FS.nodePermissions(dir, "wx");
            if (errCode) {
              return errCode;
            }
            if (isdir) {
              if (!FS.isDir(node.mode)) {
                return 54;
              }
              if (FS.isRoot(node) || FS.getPath(node) === FS.cwd()) {
                return 10;
              }
            } else {
              if (FS.isDir(node.mode)) {
                return 31;
              }
            }
            return 0;
          },
          mayOpen(node, flags) {
            if (!node) {
              return 44;
            }
            if (FS.isLink(node.mode)) {
              return 32;
            } else if (FS.isDir(node.mode)) {
              if (FS.flagsToPermissionString(flags) !== "r" || flags & (512 | 64)) {
                return 31;
              }
            }
            return FS.nodePermissions(node, FS.flagsToPermissionString(flags));
          },
          checkOpExists(op, err2) {
            if (!op) {
              throw new FS.ErrnoError(err2);
            }
            return op;
          },
          MAX_OPEN_FDS: 4096,
          nextfd() {
            for (var fd = 0; fd <= FS.MAX_OPEN_FDS; fd++) {
              if (!FS.streams[fd]) {
                return fd;
              }
            }
            throw new FS.ErrnoError(33);
          },
          getStreamChecked(fd) {
            var stream = FS.getStream(fd);
            if (!stream) {
              throw new FS.ErrnoError(8);
            }
            return stream;
          },
          getStream: (fd) => FS.streams[fd],
          createStream(stream, fd = -1) {
            assert2(fd >= -1);
            stream = Object.assign(new FS.FSStream(), stream);
            if (fd == -1) {
              fd = FS.nextfd();
            }
            stream.fd = fd;
            FS.streams[fd] = stream;
            return stream;
          },
          closeStream(fd) {
            FS.streams[fd] = null;
          },
          dupStream(origStream, fd = -1) {
            var _a3, _b2;
            var stream = FS.createStream(origStream, fd);
            (_b2 = (_a3 = stream.stream_ops) == null ? void 0 : _a3.dup) == null ? void 0 : _b2.call(_a3, stream);
            return stream;
          },
          doSetAttr(stream, node, attr) {
            var setattr = stream == null ? void 0 : stream.stream_ops.setattr;
            var arg = setattr ? stream : node;
            setattr != null ? setattr : setattr = node.node_ops.setattr;
            FS.checkOpExists(setattr, 63);
            setattr(arg, attr);
          },
          chrdev_stream_ops: {
            open(stream) {
              var _a3, _b2;
              var device = FS.getDevice(stream.node.rdev);
              stream.stream_ops = device.stream_ops;
              (_b2 = (_a3 = stream.stream_ops).open) == null ? void 0 : _b2.call(_a3, stream);
            },
            llseek() {
              throw new FS.ErrnoError(70);
            }
          },
          major: (dev) => dev >> 8,
          minor: (dev) => dev & 255,
          makedev: (ma, mi) => ma << 8 | mi,
          registerDevice(dev, ops) {
            FS.devices[dev] = { stream_ops: ops };
          },
          getDevice: (dev) => FS.devices[dev],
          getMounts(mount) {
            var mounts = [];
            var check2 = [mount];
            while (check2.length) {
              var m = check2.pop();
              mounts.push(m);
              check2.push(...m.mounts);
            }
            return mounts;
          },
          syncfs(populate, callback) {
            if (typeof populate == "function") {
              callback = populate;
              populate = false;
            }
            FS.syncFSRequests++;
            if (FS.syncFSRequests > 1) {
              err(`warning: ${FS.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);
            }
            var mounts = FS.getMounts(FS.root.mount);
            var completed = 0;
            function doCallback(errCode) {
              assert2(FS.syncFSRequests > 0);
              FS.syncFSRequests--;
              return callback(errCode);
            }
            function done(errCode) {
              if (errCode) {
                if (!done.errored) {
                  done.errored = true;
                  return doCallback(errCode);
                }
                return;
              }
              if (++completed >= mounts.length) {
                doCallback(null);
              }
            }
            mounts.forEach((mount) => {
              if (!mount.type.syncfs) {
                return done(null);
              }
              mount.type.syncfs(mount, populate, done);
            });
          },
          mount(type2, opts, mountpoint) {
            if (typeof type2 == "string") {
              throw type2;
            }
            var root = mountpoint === "/";
            var pseudo = !mountpoint;
            var node;
            if (root && FS.root) {
              throw new FS.ErrnoError(10);
            } else if (!root && !pseudo) {
              var lookup2 = FS.lookupPath(mountpoint, { follow_mount: false });
              mountpoint = lookup2.path;
              node = lookup2.node;
              if (FS.isMountpoint(node)) {
                throw new FS.ErrnoError(10);
              }
              if (!FS.isDir(node.mode)) {
                throw new FS.ErrnoError(54);
              }
            }
            var mount = {
              type: type2,
              opts,
              mountpoint,
              mounts: []
            };
            var mountRoot = type2.mount(mount);
            mountRoot.mount = mount;
            mount.root = mountRoot;
            if (root) {
              FS.root = mountRoot;
            } else if (node) {
              node.mounted = mount;
              if (node.mount) {
                node.mount.mounts.push(mount);
              }
            }
            return mountRoot;
          },
          unmount(mountpoint) {
            var lookup2 = FS.lookupPath(mountpoint, { follow_mount: false });
            if (!FS.isMountpoint(lookup2.node)) {
              throw new FS.ErrnoError(28);
            }
            var node = lookup2.node;
            var mount = node.mounted;
            var mounts = FS.getMounts(mount);
            Object.keys(FS.nameTable).forEach((hash2) => {
              var current = FS.nameTable[hash2];
              while (current) {
                var next = current.name_next;
                if (mounts.includes(current.mount)) {
                  FS.destroyNode(current);
                }
                current = next;
              }
            });
            node.mounted = null;
            var idx = node.mount.mounts.indexOf(mount);
            assert2(idx !== -1);
            node.mount.mounts.splice(idx, 1);
          },
          lookup(parent, name2) {
            return parent.node_ops.lookup(parent, name2);
          },
          mknod(path, mode, dev) {
            var lookup2 = FS.lookupPath(path, { parent: true });
            var parent = lookup2.node;
            var name2 = PATH.basename(path);
            if (!name2) {
              throw new FS.ErrnoError(28);
            }
            if (name2 === "." || name2 === "..") {
              throw new FS.ErrnoError(20);
            }
            var errCode = FS.mayCreate(parent, name2);
            if (errCode) {
              throw new FS.ErrnoError(errCode);
            }
            if (!parent.node_ops.mknod) {
              throw new FS.ErrnoError(63);
            }
            return parent.node_ops.mknod(parent, name2, mode, dev);
          },
          statfs(path) {
            return FS.statfsNode(FS.lookupPath(path, { follow: true }).node);
          },
          statfsStream(stream) {
            return FS.statfsNode(stream.node);
          },
          statfsNode(node) {
            var rtn = {
              bsize: 4096,
              frsize: 4096,
              blocks: 1e6,
              bfree: 5e5,
              bavail: 5e5,
              files: FS.nextInode,
              ffree: FS.nextInode - 1,
              fsid: 42,
              flags: 2,
              namelen: 255
            };
            if (node.node_ops.statfs) {
              Object.assign(rtn, node.node_ops.statfs(node.mount.opts.root));
            }
            return rtn;
          },
          create(path, mode = 438) {
            mode &= 4095;
            mode |= 32768;
            return FS.mknod(path, mode, 0);
          },
          mkdir(path, mode = 511) {
            mode &= 511 | 512;
            mode |= 16384;
            return FS.mknod(path, mode, 0);
          },
          mkdirTree(path, mode) {
            var dirs = path.split("/");
            var d = "";
            for (var dir of dirs) {
              if (!dir)
                continue;
              if (d || PATH.isAbs(path))
                d += "/";
              d += dir;
              try {
                FS.mkdir(d, mode);
              } catch (e) {
                if (e.errno != 20)
                  throw e;
              }
            }
          },
          mkdev(path, mode, dev) {
            if (typeof dev == "undefined") {
              dev = mode;
              mode = 438;
            }
            mode |= 8192;
            return FS.mknod(path, mode, dev);
          },
          symlink(oldpath, newpath) {
            if (!PATH_FS.resolve(oldpath)) {
              throw new FS.ErrnoError(44);
            }
            var lookup2 = FS.lookupPath(newpath, { parent: true });
            var parent = lookup2.node;
            if (!parent) {
              throw new FS.ErrnoError(44);
            }
            var newname = PATH.basename(newpath);
            var errCode = FS.mayCreate(parent, newname);
            if (errCode) {
              throw new FS.ErrnoError(errCode);
            }
            if (!parent.node_ops.symlink) {
              throw new FS.ErrnoError(63);
            }
            return parent.node_ops.symlink(parent, newname, oldpath);
          },
          rename(old_path, new_path) {
            var old_dirname = PATH.dirname(old_path);
            var new_dirname = PATH.dirname(new_path);
            var old_name = PATH.basename(old_path);
            var new_name = PATH.basename(new_path);
            var lookup2, old_dir, new_dir;
            lookup2 = FS.lookupPath(old_path, { parent: true });
            old_dir = lookup2.node;
            lookup2 = FS.lookupPath(new_path, { parent: true });
            new_dir = lookup2.node;
            if (!old_dir || !new_dir)
              throw new FS.ErrnoError(44);
            if (old_dir.mount !== new_dir.mount) {
              throw new FS.ErrnoError(75);
            }
            var old_node = FS.lookupNode(old_dir, old_name);
            var relative = PATH_FS.relative(old_path, new_dirname);
            if (relative.charAt(0) !== ".") {
              throw new FS.ErrnoError(28);
            }
            relative = PATH_FS.relative(new_path, old_dirname);
            if (relative.charAt(0) !== ".") {
              throw new FS.ErrnoError(55);
            }
            var new_node;
            try {
              new_node = FS.lookupNode(new_dir, new_name);
            } catch (e) {
            }
            if (old_node === new_node) {
              return;
            }
            var isdir = FS.isDir(old_node.mode);
            var errCode = FS.mayDelete(old_dir, old_name, isdir);
            if (errCode) {
              throw new FS.ErrnoError(errCode);
            }
            errCode = new_node ? FS.mayDelete(new_dir, new_name, isdir) : FS.mayCreate(new_dir, new_name);
            if (errCode) {
              throw new FS.ErrnoError(errCode);
            }
            if (!old_dir.node_ops.rename) {
              throw new FS.ErrnoError(63);
            }
            if (FS.isMountpoint(old_node) || new_node && FS.isMountpoint(new_node)) {
              throw new FS.ErrnoError(10);
            }
            if (new_dir !== old_dir) {
              errCode = FS.nodePermissions(old_dir, "w");
              if (errCode) {
                throw new FS.ErrnoError(errCode);
              }
            }
            FS.hashRemoveNode(old_node);
            try {
              old_dir.node_ops.rename(old_node, new_dir, new_name);
              old_node.parent = new_dir;
            } catch (e) {
              throw e;
            } finally {
              FS.hashAddNode(old_node);
            }
          },
          rmdir(path) {
            var lookup2 = FS.lookupPath(path, { parent: true });
            var parent = lookup2.node;
            var name2 = PATH.basename(path);
            var node = FS.lookupNode(parent, name2);
            var errCode = FS.mayDelete(parent, name2, true);
            if (errCode) {
              throw new FS.ErrnoError(errCode);
            }
            if (!parent.node_ops.rmdir) {
              throw new FS.ErrnoError(63);
            }
            if (FS.isMountpoint(node)) {
              throw new FS.ErrnoError(10);
            }
            parent.node_ops.rmdir(parent, name2);
            FS.destroyNode(node);
          },
          readdir(path) {
            var lookup2 = FS.lookupPath(path, { follow: true });
            var node = lookup2.node;
            var readdir = FS.checkOpExists(node.node_ops.readdir, 54);
            return readdir(node);
          },
          unlink(path) {
            var lookup2 = FS.lookupPath(path, { parent: true });
            var parent = lookup2.node;
            if (!parent) {
              throw new FS.ErrnoError(44);
            }
            var name2 = PATH.basename(path);
            var node = FS.lookupNode(parent, name2);
            var errCode = FS.mayDelete(parent, name2, false);
            if (errCode) {
              throw new FS.ErrnoError(errCode);
            }
            if (!parent.node_ops.unlink) {
              throw new FS.ErrnoError(63);
            }
            if (FS.isMountpoint(node)) {
              throw new FS.ErrnoError(10);
            }
            parent.node_ops.unlink(parent, name2);
            FS.destroyNode(node);
          },
          readlink(path) {
            var lookup2 = FS.lookupPath(path);
            var link = lookup2.node;
            if (!link) {
              throw new FS.ErrnoError(44);
            }
            if (!link.node_ops.readlink) {
              throw new FS.ErrnoError(28);
            }
            return link.node_ops.readlink(link);
          },
          stat(path, dontFollow) {
            var lookup2 = FS.lookupPath(path, { follow: !dontFollow });
            var node = lookup2.node;
            var getattr = FS.checkOpExists(node.node_ops.getattr, 63);
            return getattr(node);
          },
          fstat(fd) {
            var stream = FS.getStreamChecked(fd);
            var node = stream.node;
            var getattr = stream.stream_ops.getattr;
            var arg = getattr ? stream : node;
            getattr != null ? getattr : getattr = node.node_ops.getattr;
            FS.checkOpExists(getattr, 63);
            return getattr(arg);
          },
          lstat(path) {
            return FS.stat(path, true);
          },
          doChmod(stream, node, mode, dontFollow) {
            FS.doSetAttr(stream, node, {
              mode: mode & 4095 | node.mode & -4096,
              ctime: Date.now(),
              dontFollow
            });
          },
          chmod(path, mode, dontFollow) {
            var node;
            if (typeof path == "string") {
              var lookup2 = FS.lookupPath(path, { follow: !dontFollow });
              node = lookup2.node;
            } else {
              node = path;
            }
            FS.doChmod(null, node, mode, dontFollow);
          },
          lchmod(path, mode) {
            FS.chmod(path, mode, true);
          },
          fchmod(fd, mode) {
            var stream = FS.getStreamChecked(fd);
            FS.doChmod(stream, stream.node, mode, false);
          },
          doChown(stream, node, dontFollow) {
            FS.doSetAttr(stream, node, {
              timestamp: Date.now(),
              dontFollow
              // we ignore the uid / gid for now
            });
          },
          chown(path, uid, gid, dontFollow) {
            var node;
            if (typeof path == "string") {
              var lookup2 = FS.lookupPath(path, { follow: !dontFollow });
              node = lookup2.node;
            } else {
              node = path;
            }
            FS.doChown(null, node, dontFollow);
          },
          lchown(path, uid, gid) {
            FS.chown(path, uid, gid, true);
          },
          fchown(fd, uid, gid) {
            var stream = FS.getStreamChecked(fd);
            FS.doChown(stream, stream.node, false);
          },
          doTruncate(stream, node, len2) {
            if (FS.isDir(node.mode)) {
              throw new FS.ErrnoError(31);
            }
            if (!FS.isFile(node.mode)) {
              throw new FS.ErrnoError(28);
            }
            var errCode = FS.nodePermissions(node, "w");
            if (errCode) {
              throw new FS.ErrnoError(errCode);
            }
            FS.doSetAttr(stream, node, {
              size: len2,
              timestamp: Date.now()
            });
          },
          truncate(path, len2) {
            if (len2 < 0) {
              throw new FS.ErrnoError(28);
            }
            var node;
            if (typeof path == "string") {
              var lookup2 = FS.lookupPath(path, { follow: true });
              node = lookup2.node;
            } else {
              node = path;
            }
            FS.doTruncate(null, node, len2);
          },
          ftruncate(fd, len2) {
            var stream = FS.getStreamChecked(fd);
            if (len2 < 0 || (stream.flags & 2097155) === 0) {
              throw new FS.ErrnoError(28);
            }
            FS.doTruncate(stream, stream.node, len2);
          },
          utime(path, atime, mtime) {
            var lookup2 = FS.lookupPath(path, { follow: true });
            var node = lookup2.node;
            var setattr = FS.checkOpExists(node.node_ops.setattr, 63);
            setattr(node, {
              atime,
              mtime
            });
          },
          open(path, flags, mode = 438) {
            if (path === "") {
              throw new FS.ErrnoError(44);
            }
            flags = typeof flags == "string" ? FS_modeStringToFlags(flags) : flags;
            if (flags & 64) {
              mode = mode & 4095 | 32768;
            } else {
              mode = 0;
            }
            var node;
            var isDirPath;
            if (typeof path == "object") {
              node = path;
            } else {
              isDirPath = path.endsWith("/");
              var lookup2 = FS.lookupPath(path, {
                follow: !(flags & 131072),
                noent_okay: true
              });
              node = lookup2.node;
              path = lookup2.path;
            }
            var created = false;
            if (flags & 64) {
              if (node) {
                if (flags & 128) {
                  throw new FS.ErrnoError(20);
                }
              } else if (isDirPath) {
                throw new FS.ErrnoError(31);
              } else {
                node = FS.mknod(path, mode | 511, 0);
                created = true;
              }
            }
            if (!node) {
              throw new FS.ErrnoError(44);
            }
            if (FS.isChrdev(node.mode)) {
              flags &= -513;
            }
            if (flags & 65536 && !FS.isDir(node.mode)) {
              throw new FS.ErrnoError(54);
            }
            if (!created) {
              var errCode = FS.mayOpen(node, flags);
              if (errCode) {
                throw new FS.ErrnoError(errCode);
              }
            }
            if (flags & 512 && !created) {
              FS.truncate(node, 0);
            }
            flags &= -131713;
            var stream = FS.createStream({
              node,
              path: FS.getPath(node),
              // we want the absolute path to the node
              flags,
              seekable: true,
              position: 0,
              stream_ops: node.stream_ops,
              // used by the file family libc calls (fopen, fwrite, ferror, etc.)
              ungotten: [],
              error: false
            });
            if (stream.stream_ops.open) {
              stream.stream_ops.open(stream);
            }
            if (created) {
              FS.chmod(node, mode & 511);
            }
            if (Module["logReadFiles"] && !(flags & 1)) {
              if (!(path in FS.readFiles)) {
                FS.readFiles[path] = 1;
              }
            }
            return stream;
          },
          close(stream) {
            if (FS.isClosed(stream)) {
              throw new FS.ErrnoError(8);
            }
            if (stream.getdents)
              stream.getdents = null;
            try {
              if (stream.stream_ops.close) {
                stream.stream_ops.close(stream);
              }
            } catch (e) {
              throw e;
            } finally {
              FS.closeStream(stream.fd);
            }
            stream.fd = null;
          },
          isClosed(stream) {
            return stream.fd === null;
          },
          llseek(stream, offset, whence) {
            if (FS.isClosed(stream)) {
              throw new FS.ErrnoError(8);
            }
            if (!stream.seekable || !stream.stream_ops.llseek) {
              throw new FS.ErrnoError(70);
            }
            if (whence != 0 && whence != 1 && whence != 2) {
              throw new FS.ErrnoError(28);
            }
            stream.position = stream.stream_ops.llseek(stream, offset, whence);
            stream.ungotten = [];
            return stream.position;
          },
          read(stream, buffer2, offset, length, position) {
            assert2(offset >= 0);
            if (length < 0 || position < 0) {
              throw new FS.ErrnoError(28);
            }
            if (FS.isClosed(stream)) {
              throw new FS.ErrnoError(8);
            }
            if ((stream.flags & 2097155) === 1) {
              throw new FS.ErrnoError(8);
            }
            if (FS.isDir(stream.node.mode)) {
              throw new FS.ErrnoError(31);
            }
            if (!stream.stream_ops.read) {
              throw new FS.ErrnoError(28);
            }
            var seeking = typeof position != "undefined";
            if (!seeking) {
              position = stream.position;
            } else if (!stream.seekable) {
              throw new FS.ErrnoError(70);
            }
            var bytesRead = stream.stream_ops.read(stream, buffer2, offset, length, position);
            if (!seeking)
              stream.position += bytesRead;
            return bytesRead;
          },
          write(stream, buffer2, offset, length, position, canOwn) {
            assert2(offset >= 0);
            if (length < 0 || position < 0) {
              throw new FS.ErrnoError(28);
            }
            if (FS.isClosed(stream)) {
              throw new FS.ErrnoError(8);
            }
            if ((stream.flags & 2097155) === 0) {
              throw new FS.ErrnoError(8);
            }
            if (FS.isDir(stream.node.mode)) {
              throw new FS.ErrnoError(31);
            }
            if (!stream.stream_ops.write) {
              throw new FS.ErrnoError(28);
            }
            if (stream.seekable && stream.flags & 1024) {
              FS.llseek(stream, 0, 2);
            }
            var seeking = typeof position != "undefined";
            if (!seeking) {
              position = stream.position;
            } else if (!stream.seekable) {
              throw new FS.ErrnoError(70);
            }
            var bytesWritten = stream.stream_ops.write(stream, buffer2, offset, length, position, canOwn);
            if (!seeking)
              stream.position += bytesWritten;
            return bytesWritten;
          },
          mmap(stream, length, position, prot, flags) {
            if ((prot & 2) !== 0 && (flags & 2) === 0 && (stream.flags & 2097155) !== 2) {
              throw new FS.ErrnoError(2);
            }
            if ((stream.flags & 2097155) === 1) {
              throw new FS.ErrnoError(2);
            }
            if (!stream.stream_ops.mmap) {
              throw new FS.ErrnoError(43);
            }
            if (!length) {
              throw new FS.ErrnoError(28);
            }
            return stream.stream_ops.mmap(stream, length, position, prot, flags);
          },
          msync(stream, buffer2, offset, length, mmapFlags) {
            assert2(offset >= 0);
            if (!stream.stream_ops.msync) {
              return 0;
            }
            return stream.stream_ops.msync(stream, buffer2, offset, length, mmapFlags);
          },
          ioctl(stream, cmd, arg) {
            if (!stream.stream_ops.ioctl) {
              throw new FS.ErrnoError(59);
            }
            return stream.stream_ops.ioctl(stream, cmd, arg);
          },
          readFile(path, opts = {}) {
            opts.flags = opts.flags || 0;
            opts.encoding = opts.encoding || "binary";
            if (opts.encoding !== "utf8" && opts.encoding !== "binary") {
              throw new Error(`Invalid encoding type "${opts.encoding}"`);
            }
            var ret;
            var stream = FS.open(path, opts.flags);
            var stat = FS.stat(path);
            var length = stat.size;
            var buf = new Uint8Array(length);
            FS.read(stream, buf, 0, length, 0);
            if (opts.encoding === "utf8") {
              ret = UTF8ArrayToString(buf);
            } else if (opts.encoding === "binary") {
              ret = buf;
            }
            FS.close(stream);
            return ret;
          },
          writeFile(path, data, opts = {}) {
            opts.flags = opts.flags || 577;
            var stream = FS.open(path, opts.flags, opts.mode);
            if (typeof data == "string") {
              var buf = new Uint8Array(lengthBytesUTF8(data) + 1);
              var actualNumBytes = stringToUTF8Array(data, buf, 0, buf.length);
              FS.write(stream, buf, 0, actualNumBytes, void 0, opts.canOwn);
            } else if (ArrayBuffer.isView(data)) {
              FS.write(stream, data, 0, data.byteLength, void 0, opts.canOwn);
            } else {
              throw new Error("Unsupported data type");
            }
            FS.close(stream);
          },
          cwd: () => FS.currentPath,
          chdir(path) {
            var lookup2 = FS.lookupPath(path, { follow: true });
            if (lookup2.node === null) {
              throw new FS.ErrnoError(44);
            }
            if (!FS.isDir(lookup2.node.mode)) {
              throw new FS.ErrnoError(54);
            }
            var errCode = FS.nodePermissions(lookup2.node, "x");
            if (errCode) {
              throw new FS.ErrnoError(errCode);
            }
            FS.currentPath = lookup2.path;
          },
          createDefaultDirectories() {
            FS.mkdir("/tmp");
            FS.mkdir("/home");
            FS.mkdir("/home/web_user");
          },
          createDefaultDevices() {
            FS.mkdir("/dev");
            FS.registerDevice(FS.makedev(1, 3), {
              read: () => 0,
              write: (stream, buffer2, offset, length, pos) => length,
              llseek: () => 0
            });
            FS.mkdev("/dev/null", FS.makedev(1, 3));
            TTY.register(FS.makedev(5, 0), TTY.default_tty_ops);
            TTY.register(FS.makedev(6, 0), TTY.default_tty1_ops);
            FS.mkdev("/dev/tty", FS.makedev(5, 0));
            FS.mkdev("/dev/tty1", FS.makedev(6, 0));
            var randomBuffer = new Uint8Array(1024), randomLeft = 0;
            var randomByte = () => {
              if (randomLeft === 0) {
                randomFill(randomBuffer);
                randomLeft = randomBuffer.byteLength;
              }
              return randomBuffer[--randomLeft];
            };
            FS.createDevice("/dev", "random", randomByte);
            FS.createDevice("/dev", "urandom", randomByte);
            FS.mkdir("/dev/shm");
            FS.mkdir("/dev/shm/tmp");
          },
          createSpecialDirectories() {
            FS.mkdir("/proc");
            var proc_self = FS.mkdir("/proc/self");
            FS.mkdir("/proc/self/fd");
            FS.mount({
              mount() {
                var node = FS.createNode(proc_self, "fd", 16895, 73);
                node.stream_ops = {
                  llseek: MEMFS.stream_ops.llseek
                };
                node.node_ops = {
                  lookup(parent, name2) {
                    var fd = +name2;
                    var stream = FS.getStreamChecked(fd);
                    var ret = {
                      parent: null,
                      mount: { mountpoint: "fake" },
                      node_ops: { readlink: () => stream.path },
                      id: fd + 1
                    };
                    ret.parent = ret;
                    return ret;
                  },
                  readdir() {
                    return Array.from(FS.streams.entries()).filter(([k, v]) => v).map(([k, v]) => k.toString());
                  }
                };
                return node;
              }
            }, {}, "/proc/self/fd");
          },
          createStandardStreams(input, output, error2) {
            if (input) {
              FS.createDevice("/dev", "stdin", input);
            } else {
              FS.symlink("/dev/tty", "/dev/stdin");
            }
            if (output) {
              FS.createDevice("/dev", "stdout", null, output);
            } else {
              FS.symlink("/dev/tty", "/dev/stdout");
            }
            if (error2) {
              FS.createDevice("/dev", "stderr", null, error2);
            } else {
              FS.symlink("/dev/tty1", "/dev/stderr");
            }
            var stdin = FS.open("/dev/stdin", 0);
            var stdout = FS.open("/dev/stdout", 1);
            var stderr = FS.open("/dev/stderr", 1);
            assert2(stdin.fd === 0, `invalid handle for stdin (${stdin.fd})`);
            assert2(stdout.fd === 1, `invalid handle for stdout (${stdout.fd})`);
            assert2(stderr.fd === 2, `invalid handle for stderr (${stderr.fd})`);
          },
          staticInit() {
            FS.nameTable = new Array(4096);
            FS.mount(MEMFS, {}, "/");
            FS.createDefaultDirectories();
            FS.createDefaultDevices();
            FS.createSpecialDirectories();
            FS.filesystems = {
              "MEMFS": MEMFS,
              "IDBFS": IDBFS
            };
          },
          init(input, output, error2) {
            assert2(!FS.initialized, "FS.init was previously called. If you want to initialize later with custom parameters, remove any earlier calls (note that one is automatically added to the generated code)");
            FS.initialized = true;
            input != null ? input : input = Module["stdin"];
            output != null ? output : output = Module["stdout"];
            error2 != null ? error2 : error2 = Module["stderr"];
            FS.createStandardStreams(input, output, error2);
          },
          quit() {
            FS.initialized = false;
            _fflush(0);
            for (var stream of FS.streams) {
              if (stream) {
                FS.close(stream);
              }
            }
          },
          findObject(path, dontResolveLastLink) {
            var ret = FS.analyzePath(path, dontResolveLastLink);
            if (!ret.exists) {
              return null;
            }
            return ret.object;
          },
          analyzePath(path, dontResolveLastLink) {
            try {
              var lookup2 = FS.lookupPath(path, { follow: !dontResolveLastLink });
              path = lookup2.path;
            } catch (e) {
            }
            var ret = {
              isRoot: false,
              exists: false,
              error: 0,
              name: null,
              path: null,
              object: null,
              parentExists: false,
              parentPath: null,
              parentObject: null
            };
            try {
              var lookup2 = FS.lookupPath(path, { parent: true });
              ret.parentExists = true;
              ret.parentPath = lookup2.path;
              ret.parentObject = lookup2.node;
              ret.name = PATH.basename(path);
              lookup2 = FS.lookupPath(path, { follow: !dontResolveLastLink });
              ret.exists = true;
              ret.path = lookup2.path;
              ret.object = lookup2.node;
              ret.name = lookup2.node.name;
              ret.isRoot = lookup2.path === "/";
            } catch (e) {
              ret.error = e.errno;
            }
            return ret;
          },
          createPath(parent, path, canRead, canWrite) {
            parent = typeof parent == "string" ? parent : FS.getPath(parent);
            var parts = path.split("/").reverse();
            while (parts.length) {
              var part = parts.pop();
              if (!part)
                continue;
              var current = PATH.join2(parent, part);
              try {
                FS.mkdir(current);
              } catch (e) {
                if (e.errno != 20)
                  throw e;
              }
              parent = current;
            }
            return current;
          },
          createFile(parent, name2, properties2, canRead, canWrite) {
            var path = PATH.join2(typeof parent == "string" ? parent : FS.getPath(parent), name2);
            var mode = FS_getMode(canRead, canWrite);
            return FS.create(path, mode);
          },
          createDataFile(parent, name2, data, canRead, canWrite, canOwn) {
            var path = name2;
            if (parent) {
              parent = typeof parent == "string" ? parent : FS.getPath(parent);
              path = name2 ? PATH.join2(parent, name2) : parent;
            }
            var mode = FS_getMode(canRead, canWrite);
            var node = FS.create(path, mode);
            if (data) {
              if (typeof data == "string") {
                var arr = new Array(data.length);
                for (var i2 = 0, len2 = data.length; i2 < len2; ++i2)
                  arr[i2] = data.charCodeAt(i2);
                data = arr;
              }
              FS.chmod(node, mode | 146);
              var stream = FS.open(node, 577);
              FS.write(stream, data, 0, data.length, 0, canOwn);
              FS.close(stream);
              FS.chmod(node, mode);
            }
          },
          createDevice(parent, name2, input, output) {
            var _a4;
            var _a3;
            var path = PATH.join2(typeof parent == "string" ? parent : FS.getPath(parent), name2);
            var mode = FS_getMode(!!input, !!output);
            (_a4 = (_a3 = FS.createDevice).major) != null ? _a4 : _a3.major = 64;
            var dev = FS.makedev(FS.createDevice.major++, 0);
            FS.registerDevice(dev, {
              open(stream) {
                stream.seekable = false;
              },
              close(stream) {
                var _a22;
                if ((_a22 = output == null ? void 0 : output.buffer) == null ? void 0 : _a22.length) {
                  output(10);
                }
              },
              read(stream, buffer2, offset, length, pos) {
                var bytesRead = 0;
                for (var i2 = 0; i2 < length; i2++) {
                  var result2;
                  try {
                    result2 = input();
                  } catch (e) {
                    throw new FS.ErrnoError(29);
                  }
                  if (result2 === void 0 && bytesRead === 0) {
                    throw new FS.ErrnoError(6);
                  }
                  if (result2 === null || result2 === void 0)
                    break;
                  bytesRead++;
                  buffer2[offset + i2] = result2;
                }
                if (bytesRead) {
                  stream.node.atime = Date.now();
                }
                return bytesRead;
              },
              write(stream, buffer2, offset, length, pos) {
                for (var i2 = 0; i2 < length; i2++) {
                  try {
                    output(buffer2[offset + i2]);
                  } catch (e) {
                    throw new FS.ErrnoError(29);
                  }
                }
                if (length) {
                  stream.node.mtime = stream.node.ctime = Date.now();
                }
                return i2;
              }
            });
            return FS.mkdev(path, mode, dev);
          },
          forceLoadFile(obj) {
            if (obj.isDevice || obj.isFolder || obj.link || obj.contents)
              return true;
            if (typeof XMLHttpRequest != "undefined") {
              throw new Error("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.");
            } else {
              try {
                obj.contents = readBinary(obj.url);
                obj.usedBytes = obj.contents.length;
              } catch (e) {
                throw new FS.ErrnoError(29);
              }
            }
          },
          createLazyFile(parent, name2, url2, canRead, canWrite) {
            class LazyUint8Array {
              constructor() {
                __publicField(this, "lengthKnown", false);
                __publicField(this, "chunks", []);
              }
              // Loaded chunks. Index is the chunk number
              get(idx) {
                if (idx > this.length - 1 || idx < 0) {
                  return void 0;
                }
                var chunkOffset = idx % this.chunkSize;
                var chunkNum = idx / this.chunkSize | 0;
                return this.getter(chunkNum)[chunkOffset];
              }
              setDataGetter(getter) {
                this.getter = getter;
              }
              cacheLength() {
                var xhr = new XMLHttpRequest();
                xhr.open("HEAD", url2, false);
                xhr.send(null);
                if (!(xhr.status >= 200 && xhr.status < 300 || xhr.status === 304))
                  throw new Error("Couldn't load " + url2 + ". Status: " + xhr.status);
                var datalength = Number(xhr.getResponseHeader("Content-length"));
                var header;
                var hasByteServing = (header = xhr.getResponseHeader("Accept-Ranges")) && header === "bytes";
                var usesGzip = (header = xhr.getResponseHeader("Content-Encoding")) && header === "gzip";
                var chunkSize = 1024 * 1024;
                if (!hasByteServing)
                  chunkSize = datalength;
                var doXHR = (from, to) => {
                  if (from > to)
                    throw new Error("invalid range (" + from + ", " + to + ") or no bytes requested!");
                  if (to > datalength - 1)
                    throw new Error("only " + datalength + " bytes available! programmer error!");
                  var xhr2 = new XMLHttpRequest();
                  xhr2.open("GET", url2, false);
                  if (datalength !== chunkSize)
                    xhr2.setRequestHeader("Range", "bytes=" + from + "-" + to);
                  xhr2.responseType = "arraybuffer";
                  if (xhr2.overrideMimeType) {
                    xhr2.overrideMimeType("text/plain; charset=x-user-defined");
                  }
                  xhr2.send(null);
                  if (!(xhr2.status >= 200 && xhr2.status < 300 || xhr2.status === 304))
                    throw new Error("Couldn't load " + url2 + ". Status: " + xhr2.status);
                  if (xhr2.response !== void 0) {
                    return new Uint8Array(
                      /** @type{Array<number>} */
                      xhr2.response || []
                    );
                  }
                  return intArrayFromString(xhr2.responseText || "");
                };
                var lazyArray2 = this;
                lazyArray2.setDataGetter((chunkNum) => {
                  var start = chunkNum * chunkSize;
                  var end = (chunkNum + 1) * chunkSize - 1;
                  end = Math.min(end, datalength - 1);
                  if (typeof lazyArray2.chunks[chunkNum] == "undefined") {
                    lazyArray2.chunks[chunkNum] = doXHR(start, end);
                  }
                  if (typeof lazyArray2.chunks[chunkNum] == "undefined")
                    throw new Error("doXHR failed!");
                  return lazyArray2.chunks[chunkNum];
                });
                if (usesGzip || !datalength) {
                  chunkSize = datalength = 1;
                  datalength = this.getter(0).length;
                  chunkSize = datalength;
                  out("LazyFiles on gzip forces download of the whole file when length is accessed");
                }
                this._length = datalength;
                this._chunkSize = chunkSize;
                this.lengthKnown = true;
              }
              get length() {
                if (!this.lengthKnown) {
                  this.cacheLength();
                }
                return this._length;
              }
              get chunkSize() {
                if (!this.lengthKnown) {
                  this.cacheLength();
                }
                return this._chunkSize;
              }
            }
            if (typeof XMLHttpRequest != "undefined") {
              throw "Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc";
              var lazyArray = new LazyUint8Array();
              var properties2 = { isDevice: false, contents: lazyArray };
            } else {
              var properties2 = { isDevice: false, url: url2 };
            }
            var node = FS.createFile(parent, name2, properties2, canRead, canWrite);
            if (properties2.contents) {
              node.contents = properties2.contents;
            } else if (properties2.url) {
              node.contents = null;
              node.url = properties2.url;
            }
            Object.defineProperties(node, {
              usedBytes: {
                get: function() {
                  return this.contents.length;
                }
              }
            });
            var stream_ops = {};
            var keys = Object.keys(node.stream_ops);
            keys.forEach((key) => {
              var fn = node.stream_ops[key];
              stream_ops[key] = (...args) => {
                FS.forceLoadFile(node);
                return fn(...args);
              };
            });
            function writeChunks(stream, buffer2, offset, length, position) {
              var contents = stream.node.contents;
              if (position >= contents.length)
                return 0;
              var size = Math.min(contents.length - position, length);
              assert2(size >= 0);
              if (contents.slice) {
                for (var i2 = 0; i2 < size; i2++) {
                  buffer2[offset + i2] = contents[position + i2];
                }
              } else {
                for (var i2 = 0; i2 < size; i2++) {
                  buffer2[offset + i2] = contents.get(position + i2);
                }
              }
              return size;
            }
            stream_ops.read = (stream, buffer2, offset, length, position) => {
              FS.forceLoadFile(node);
              return writeChunks(stream, buffer2, offset, length, position);
            };
            stream_ops.mmap = (stream, length, position, prot, flags) => {
              FS.forceLoadFile(node);
              var ptr = mmapAlloc();
              if (!ptr) {
                throw new FS.ErrnoError(48);
              }
              writeChunks(stream, HEAP8, ptr, length, position);
              return { ptr, allocated: true };
            };
            node.stream_ops = stream_ops;
            return node;
          },
          absolutePath() {
            abort("FS.absolutePath has been removed; use PATH_FS.resolve instead");
          },
          createFolder() {
            abort("FS.createFolder has been removed; use FS.mkdir instead");
          },
          createLink() {
            abort("FS.createLink has been removed; use FS.symlink instead");
          },
          joinPath() {
            abort("FS.joinPath has been removed; use PATH.join instead");
          },
          mmapAlloc() {
            abort("FS.mmapAlloc has been replaced by the top level function mmapAlloc");
          },
          standardizePath() {
            abort("FS.standardizePath has been removed; use PATH.normalize instead");
          }
        };
        var SYSCALLS = {
          DEFAULT_POLLMASK: 5,
          calculateAt(dirfd, path, allowEmpty) {
            if (PATH.isAbs(path)) {
              return path;
            }
            var dir;
            if (dirfd === -100) {
              dir = FS.cwd();
            } else {
              var dirstream = SYSCALLS.getStreamFromFD(dirfd);
              dir = dirstream.path;
            }
            if (path.length == 0) {
              if (!allowEmpty) {
                throw new FS.ErrnoError(44);
              }
              return dir;
            }
            return dir + "/" + path;
          },
          writeStat(buf, stat) {
            HEAP32[buf >> 2] = stat.dev;
            HEAP32[buf + 4 >> 2] = stat.mode;
            HEAPU32[buf + 8 >> 2] = stat.nlink;
            HEAP32[buf + 12 >> 2] = stat.uid;
            HEAP32[buf + 16 >> 2] = stat.gid;
            HEAP32[buf + 20 >> 2] = stat.rdev;
            HEAP64[buf + 24 >> 3] = BigInt(stat.size);
            HEAP32[buf + 32 >> 2] = 4096;
            HEAP32[buf + 36 >> 2] = stat.blocks;
            var atime = stat.atime.getTime();
            var mtime = stat.mtime.getTime();
            var ctime = stat.ctime.getTime();
            HEAP64[buf + 40 >> 3] = BigInt(Math.floor(atime / 1e3));
            HEAPU32[buf + 48 >> 2] = atime % 1e3 * 1e3 * 1e3;
            HEAP64[buf + 56 >> 3] = BigInt(Math.floor(mtime / 1e3));
            HEAPU32[buf + 64 >> 2] = mtime % 1e3 * 1e3 * 1e3;
            HEAP64[buf + 72 >> 3] = BigInt(Math.floor(ctime / 1e3));
            HEAPU32[buf + 80 >> 2] = ctime % 1e3 * 1e3 * 1e3;
            HEAP64[buf + 88 >> 3] = BigInt(stat.ino);
            return 0;
          },
          writeStatFs(buf, stats) {
            HEAP32[buf + 4 >> 2] = stats.bsize;
            HEAP32[buf + 40 >> 2] = stats.bsize;
            HEAP32[buf + 8 >> 2] = stats.blocks;
            HEAP32[buf + 12 >> 2] = stats.bfree;
            HEAP32[buf + 16 >> 2] = stats.bavail;
            HEAP32[buf + 20 >> 2] = stats.files;
            HEAP32[buf + 24 >> 2] = stats.ffree;
            HEAP32[buf + 28 >> 2] = stats.fsid;
            HEAP32[buf + 44 >> 2] = stats.flags;
            HEAP32[buf + 36 >> 2] = stats.namelen;
          },
          doMsync(addr, stream, len2, flags, offset) {
            if (!FS.isFile(stream.node.mode)) {
              throw new FS.ErrnoError(43);
            }
            if (flags & 2) {
              return 0;
            }
            var buffer2 = HEAPU8.slice(addr, addr + len2);
            FS.msync(stream, buffer2, offset, len2, flags);
          },
          getStreamFromFD(fd) {
            var stream = FS.getStreamChecked(fd);
            return stream;
          },
          varargs: void 0,
          getStr(ptr) {
            var ret = UTF8ToString(ptr);
            return ret;
          }
        };
        function ___syscall_fcntl64(fd, cmd, varargs) {
          SYSCALLS.varargs = varargs;
          try {
            var stream = SYSCALLS.getStreamFromFD(fd);
            switch (cmd) {
              case 0: {
                var arg = syscallGetVarargI();
                if (arg < 0) {
                  return -28;
                }
                while (FS.streams[arg]) {
                  arg++;
                }
                var newStream;
                newStream = FS.dupStream(stream, arg);
                return newStream.fd;
              }
              case 1:
              case 2:
                return 0;
              case 3:
                return stream.flags;
              case 4: {
                var arg = syscallGetVarargI();
                stream.flags |= arg;
                return 0;
              }
              case 12: {
                var arg = syscallGetVarargP();
                var offset = 0;
                HEAP16[arg + offset >> 1] = 2;
                return 0;
              }
              case 13:
              case 14:
                return 0;
            }
            return -28;
          } catch (e) {
            if (typeof FS == "undefined" || !(e.name === "ErrnoError"))
              throw e;
            return -e.errno;
          }
        }
        function ___syscall_fstat64(fd, buf) {
          try {
            return SYSCALLS.writeStat(buf, FS.fstat(fd));
          } catch (e) {
            if (typeof FS == "undefined" || !(e.name === "ErrnoError"))
              throw e;
            return -e.errno;
          }
        }
        function ___syscall_ioctl(fd, op, varargs) {
          SYSCALLS.varargs = varargs;
          try {
            var stream = SYSCALLS.getStreamFromFD(fd);
            switch (op) {
              case 21509: {
                if (!stream.tty)
                  return -59;
                return 0;
              }
              case 21505: {
                if (!stream.tty)
                  return -59;
                if (stream.tty.ops.ioctl_tcgets) {
                  var termios = stream.tty.ops.ioctl_tcgets(stream);
                  var argp = syscallGetVarargP();
                  HEAP32[argp >> 2] = termios.c_iflag || 0;
                  HEAP32[argp + 4 >> 2] = termios.c_oflag || 0;
                  HEAP32[argp + 8 >> 2] = termios.c_cflag || 0;
                  HEAP32[argp + 12 >> 2] = termios.c_lflag || 0;
                  for (var i2 = 0; i2 < 32; i2++) {
                    HEAP8[argp + i2 + 17] = termios.c_cc[i2] || 0;
                  }
                  return 0;
                }
                return 0;
              }
              case 21510:
              case 21511:
              case 21512: {
                if (!stream.tty)
                  return -59;
                return 0;
              }
              case 21506:
              case 21507:
              case 21508: {
                if (!stream.tty)
                  return -59;
                if (stream.tty.ops.ioctl_tcsets) {
                  var argp = syscallGetVarargP();
                  var c_iflag = HEAP32[argp >> 2];
                  var c_oflag = HEAP32[argp + 4 >> 2];
                  var c_cflag = HEAP32[argp + 8 >> 2];
                  var c_lflag = HEAP32[argp + 12 >> 2];
                  var c_cc = [];
                  for (var i2 = 0; i2 < 32; i2++) {
                    c_cc.push(HEAP8[argp + i2 + 17]);
                  }
                  return stream.tty.ops.ioctl_tcsets(stream.tty, op, { c_iflag, c_oflag, c_cflag, c_lflag, c_cc });
                }
                return 0;
              }
              case 21519: {
                if (!stream.tty)
                  return -59;
                var argp = syscallGetVarargP();
                HEAP32[argp >> 2] = 0;
                return 0;
              }
              case 21520: {
                if (!stream.tty)
                  return -59;
                return -28;
              }
              case 21531: {
                var argp = syscallGetVarargP();
                return FS.ioctl(stream, op, argp);
              }
              case 21523: {
                if (!stream.tty)
                  return -59;
                if (stream.tty.ops.ioctl_tiocgwinsz) {
                  var winsize = stream.tty.ops.ioctl_tiocgwinsz(stream.tty);
                  var argp = syscallGetVarargP();
                  HEAP16[argp >> 1] = winsize[0];
                  HEAP16[argp + 2 >> 1] = winsize[1];
                }
                return 0;
              }
              case 21524: {
                if (!stream.tty)
                  return -59;
                return 0;
              }
              case 21515: {
                if (!stream.tty)
                  return -59;
                return 0;
              }
              default:
                return -28;
            }
          } catch (e) {
            if (typeof FS == "undefined" || !(e.name === "ErrnoError"))
              throw e;
            return -e.errno;
          }
        }
        function ___syscall_lstat64(path, buf) {
          try {
            path = SYSCALLS.getStr(path);
            return SYSCALLS.writeStat(buf, FS.lstat(path));
          } catch (e) {
            if (typeof FS == "undefined" || !(e.name === "ErrnoError"))
              throw e;
            return -e.errno;
          }
        }
        function ___syscall_newfstatat(dirfd, path, buf, flags) {
          try {
            path = SYSCALLS.getStr(path);
            var nofollow = flags & 256;
            var allowEmpty = flags & 4096;
            flags = flags & ~6400;
            assert2(!flags, `unknown flags in __syscall_newfstatat: ${flags}`);
            path = SYSCALLS.calculateAt(dirfd, path, allowEmpty);
            return SYSCALLS.writeStat(buf, nofollow ? FS.lstat(path) : FS.stat(path));
          } catch (e) {
            if (typeof FS == "undefined" || !(e.name === "ErrnoError"))
              throw e;
            return -e.errno;
          }
        }
        function ___syscall_openat(dirfd, path, flags, varargs) {
          SYSCALLS.varargs = varargs;
          try {
            path = SYSCALLS.getStr(path);
            path = SYSCALLS.calculateAt(dirfd, path);
            var mode = varargs ? syscallGetVarargI() : 0;
            return FS.open(path, flags, mode).fd;
          } catch (e) {
            if (typeof FS == "undefined" || !(e.name === "ErrnoError"))
              throw e;
            return -e.errno;
          }
        }
        function ___syscall_stat64(path, buf) {
          try {
            path = SYSCALLS.getStr(path);
            return SYSCALLS.writeStat(buf, FS.stat(path));
          } catch (e) {
            if (typeof FS == "undefined" || !(e.name === "ErrnoError"))
              throw e;
            return -e.errno;
          }
        }
        var getCppExceptionTag = () => ___cpp_exception;
        var getCppExceptionThrownObjectFromWebAssemblyException = (ex) => {
          var unwind_header = ex.getArg(getCppExceptionTag(), 0);
          return ___thrown_object_from_unwind_exception(unwind_header);
        };
        var stackSave = () => _emscripten_stack_get_current();
        var stackRestore = (val) => __emscripten_stack_restore(val);
        var stackAlloc = (sz) => __emscripten_stack_alloc(sz);
        var getExceptionMessageCommon = (ptr) => {
          var sp = stackSave();
          var type_addr_addr = stackAlloc(4);
          var message_addr_addr = stackAlloc(4);
          ___get_exception_message(ptr, type_addr_addr, message_addr_addr);
          var type_addr = HEAPU32[type_addr_addr >> 2];
          var message_addr = HEAPU32[message_addr_addr >> 2];
          var type2 = UTF8ToString(type_addr);
          _free(type_addr);
          var message;
          if (message_addr) {
            message = UTF8ToString(message_addr);
            _free(message_addr);
          }
          stackRestore(sp);
          return [type2, message];
        };
        var getExceptionMessage = (ex) => {
          var ptr = getCppExceptionThrownObjectFromWebAssemblyException(ex);
          return getExceptionMessageCommon(ptr);
        };
        var ___throw_exception_with_stack_trace = (ex) => {
          var e = new WebAssembly.Exception(getCppExceptionTag(), [ex], { traceStack: true });
          e.message = getExceptionMessage(e);
          throw e;
        };
        var __abort_js = () => abort("native code called abort()");
        var embind_init_charCodes = () => {
          var codes = new Array(256);
          for (var i2 = 0; i2 < 256; ++i2) {
            codes[i2] = String.fromCharCode(i2);
          }
          embind_charCodes = codes;
        };
        var embind_charCodes;
        var readLatin1String = (ptr) => {
          var ret = "";
          var c = ptr;
          while (HEAPU8[c]) {
            ret += embind_charCodes[HEAPU8[c++]];
          }
          return ret;
        };
        var awaitingDependencies = {};
        var registeredTypes = {};
        var typeDependencies = {};
        var BindingError = class BindingError extends Error {
          constructor(message) {
            super(message);
            this.name = "BindingError";
          }
        };
        var throwBindingError = (message) => {
          throw new BindingError(message);
        };
        function sharedRegisterType(rawType, registeredInstance, options = {}) {
          var name2 = registeredInstance.name;
          if (!rawType) {
            throwBindingError(`type "${name2}" must have a positive integer typeid pointer`);
          }
          if (registeredTypes.hasOwnProperty(rawType)) {
            if (options.ignoreDuplicateRegistrations) {
              return;
            } else {
              throwBindingError(`Cannot register type '${name2}' twice`);
            }
          }
          registeredTypes[rawType] = registeredInstance;
          delete typeDependencies[rawType];
          if (awaitingDependencies.hasOwnProperty(rawType)) {
            var callbacks = awaitingDependencies[rawType];
            delete awaitingDependencies[rawType];
            callbacks.forEach((cb) => cb());
          }
        }
        function registerType(rawType, registeredInstance, options = {}) {
          if (registeredInstance.argPackAdvance === void 0) {
            throw new TypeError("registerType registeredInstance requires argPackAdvance");
          }
          return sharedRegisterType(rawType, registeredInstance, options);
        }
        var integerReadValueFromPointer = (name2, width, signed) => {
          switch (width) {
            case 1:
              return signed ? (pointer) => HEAP8[pointer] : (pointer) => HEAPU8[pointer];
            case 2:
              return signed ? (pointer) => HEAP16[pointer >> 1] : (pointer) => HEAPU16[pointer >> 1];
            case 4:
              return signed ? (pointer) => HEAP32[pointer >> 2] : (pointer) => HEAPU32[pointer >> 2];
            case 8:
              return signed ? (pointer) => HEAP64[pointer >> 3] : (pointer) => HEAPU64[pointer >> 3];
            default:
              throw new TypeError(`invalid integer width (${width}): ${name2}`);
          }
        };
        var embindRepr = (v) => {
          if (v === null) {
            return "null";
          }
          var t = typeof v;
          if (t === "object" || t === "array" || t === "function") {
            return v.toString();
          } else {
            return "" + v;
          }
        };
        var assertIntegerRange = (typeName, value, minRange, maxRange) => {
          if (value < minRange || value > maxRange) {
            throw new TypeError(`Passing a number "${embindRepr(value)}" from JS side to C/C++ side to an argument of type "${typeName}", which is outside the valid range [${minRange}, ${maxRange}]!`);
          }
        };
        var __embind_register_bigint = (primitiveType, name2, size, minRange, maxRange) => {
          name2 = readLatin1String(name2);
          const isUnsignedType = minRange === /* @__PURE__ */ BigInt("0");
          let fromWireType = (value) => value;
          if (isUnsignedType) {
            const bitSize = size * 8;
            fromWireType = (value) => {
              return BigInt.asUintN(bitSize, value);
            };
            maxRange = fromWireType(maxRange);
          }
          registerType(primitiveType, {
            name: name2,
            "fromWireType": fromWireType,
            "toWireType": (destructors, value) => {
              if (typeof value == "number") {
                value = BigInt(value);
              } else if (typeof value != "bigint") {
                throw new TypeError(`Cannot convert "${embindRepr(value)}" to ${this.name}`);
              }
              assertIntegerRange(name2, value, minRange, maxRange);
              return value;
            },
            argPackAdvance: GenericWireTypeSize,
            "readValueFromPointer": integerReadValueFromPointer(name2, size, !isUnsignedType),
            destructorFunction: null
            // This type does not need a destructor
          });
        };
        var GenericWireTypeSize = 8;
        var __embind_register_bool = (rawType, name2, trueValue, falseValue) => {
          name2 = readLatin1String(name2);
          registerType(rawType, {
            name: name2,
            "fromWireType": function(wt) {
              return !!wt;
            },
            "toWireType": function(destructors, o) {
              return o ? trueValue : falseValue;
            },
            argPackAdvance: GenericWireTypeSize,
            "readValueFromPointer": function(pointer) {
              return this["fromWireType"](HEAPU8[pointer]);
            },
            destructorFunction: null
            // This type does not need a destructor
          });
        };
        var shallowCopyInternalPointer = (o) => {
          return {
            count: o.count,
            deleteScheduled: o.deleteScheduled,
            preservePointerOnDelete: o.preservePointerOnDelete,
            ptr: o.ptr,
            ptrType: o.ptrType,
            smartPtr: o.smartPtr,
            smartPtrType: o.smartPtrType
          };
        };
        var throwInstanceAlreadyDeleted = (obj) => {
          function getInstanceTypeName(handle) {
            return handle.$$.ptrType.registeredClass.name;
          }
          throwBindingError(getInstanceTypeName(obj) + " instance already deleted");
        };
        var finalizationRegistry = false;
        var detachFinalizer = (handle) => {
        };
        var runDestructor = ($$) => {
          if ($$.smartPtr) {
            $$.smartPtrType.rawDestructor($$.smartPtr);
          } else {
            $$.ptrType.registeredClass.rawDestructor($$.ptr);
          }
        };
        var releaseClassHandle = ($$) => {
          $$.count.value -= 1;
          var toDelete = 0 === $$.count.value;
          if (toDelete) {
            runDestructor($$);
          }
        };
        var downcastPointer = (ptr, ptrClass, desiredClass) => {
          if (ptrClass === desiredClass) {
            return ptr;
          }
          if (void 0 === desiredClass.baseClass) {
            return null;
          }
          var rv = downcastPointer(ptr, ptrClass, desiredClass.baseClass);
          if (rv === null) {
            return null;
          }
          return desiredClass.downcast(rv);
        };
        var registeredPointers = {};
        var registeredInstances = {};
        var getBasestPointer = (class_, ptr) => {
          if (ptr === void 0) {
            throwBindingError("ptr should not be undefined");
          }
          while (class_.baseClass) {
            ptr = class_.upcast(ptr);
            class_ = class_.baseClass;
          }
          return ptr;
        };
        var getInheritedInstance = (class_, ptr) => {
          ptr = getBasestPointer(class_, ptr);
          return registeredInstances[ptr];
        };
        var InternalError = class InternalError extends Error {
          constructor(message) {
            super(message);
            this.name = "InternalError";
          }
        };
        var throwInternalError = (message) => {
          throw new InternalError(message);
        };
        var makeClassHandle = (prototype, record2) => {
          if (!record2.ptrType || !record2.ptr) {
            throwInternalError("makeClassHandle requires ptr and ptrType");
          }
          var hasSmartPtrType = !!record2.smartPtrType;
          var hasSmartPtr = !!record2.smartPtr;
          if (hasSmartPtrType !== hasSmartPtr) {
            throwInternalError("Both smartPtrType and smartPtr must be specified");
          }
          record2.count = { value: 1 };
          return attachFinalizer(Object.create(prototype, {
            $$: {
              value: record2,
              writable: true
            }
          }));
        };
        function RegisteredPointer_fromWireType(ptr) {
          var rawPointer = this.getPointee(ptr);
          if (!rawPointer) {
            this.destructor(ptr);
            return null;
          }
          var registeredInstance = getInheritedInstance(this.registeredClass, rawPointer);
          if (void 0 !== registeredInstance) {
            if (0 === registeredInstance.$$.count.value) {
              registeredInstance.$$.ptr = rawPointer;
              registeredInstance.$$.smartPtr = ptr;
              return registeredInstance["clone"]();
            } else {
              var rv = registeredInstance["clone"]();
              this.destructor(ptr);
              return rv;
            }
          }
          function makeDefaultHandle() {
            if (this.isSmartPointer) {
              return makeClassHandle(this.registeredClass.instancePrototype, {
                ptrType: this.pointeeType,
                ptr: rawPointer,
                smartPtrType: this,
                smartPtr: ptr
              });
            } else {
              return makeClassHandle(this.registeredClass.instancePrototype, {
                ptrType: this,
                ptr
              });
            }
          }
          var actualType = this.registeredClass.getActualType(rawPointer);
          var registeredPointerRecord = registeredPointers[actualType];
          if (!registeredPointerRecord) {
            return makeDefaultHandle.call(this);
          }
          var toType;
          if (this.isConst) {
            toType = registeredPointerRecord.constPointerType;
          } else {
            toType = registeredPointerRecord.pointerType;
          }
          var dp = downcastPointer(
            rawPointer,
            this.registeredClass,
            toType.registeredClass
          );
          if (dp === null) {
            return makeDefaultHandle.call(this);
          }
          if (this.isSmartPointer) {
            return makeClassHandle(toType.registeredClass.instancePrototype, {
              ptrType: toType,
              ptr: dp,
              smartPtrType: this,
              smartPtr: ptr
            });
          } else {
            return makeClassHandle(toType.registeredClass.instancePrototype, {
              ptrType: toType,
              ptr: dp
            });
          }
        }
        var attachFinalizer = (handle) => {
          if ("undefined" === typeof FinalizationRegistry) {
            attachFinalizer = (handle2) => handle2;
            return handle;
          }
          finalizationRegistry = new FinalizationRegistry((info) => {
            console.warn(info.leakWarning);
            releaseClassHandle(info.$$);
          });
          attachFinalizer = (handle2) => {
            var $$ = handle2.$$;
            var hasSmartPtr = !!$$.smartPtr;
            if (hasSmartPtr) {
              var info = { $$ };
              var cls = $$.ptrType.registeredClass;
              var err2 = new Error(`Embind found a leaked C++ instance ${cls.name} <${ptrToString($$.ptr)}>.
We'll free it automatically in this case, but this functionality is not reliable across various environments.
Make sure to invoke .delete() manually once you're done with the instance instead.
Originally allocated`);
              if ("captureStackTrace" in Error) {
                Error.captureStackTrace(err2, RegisteredPointer_fromWireType);
              }
              info.leakWarning = err2.stack.replace(/^Error: /, "");
              finalizationRegistry.register(handle2, info, handle2);
            }
            return handle2;
          };
          detachFinalizer = (handle2) => finalizationRegistry.unregister(handle2);
          return attachFinalizer(handle);
        };
        var init_ClassHandle = () => {
          let proto = ClassHandle.prototype;
          Object.assign(proto, {
            "isAliasOf"(other) {
              if (!(this instanceof ClassHandle)) {
                return false;
              }
              if (!(other instanceof ClassHandle)) {
                return false;
              }
              var leftClass = this.$$.ptrType.registeredClass;
              var left = this.$$.ptr;
              other.$$ = /** @type {Object} */
              other.$$;
              var rightClass = other.$$.ptrType.registeredClass;
              var right = other.$$.ptr;
              while (leftClass.baseClass) {
                left = leftClass.upcast(left);
                leftClass = leftClass.baseClass;
              }
              while (rightClass.baseClass) {
                right = rightClass.upcast(right);
                rightClass = rightClass.baseClass;
              }
              return leftClass === rightClass && left === right;
            },
            "clone"() {
              if (!this.$$.ptr) {
                throwInstanceAlreadyDeleted(this);
              }
              if (this.$$.preservePointerOnDelete) {
                this.$$.count.value += 1;
                return this;
              } else {
                var clone2 = attachFinalizer(Object.create(Object.getPrototypeOf(this), {
                  $$: {
                    value: shallowCopyInternalPointer(this.$$)
                  }
                }));
                clone2.$$.count.value += 1;
                clone2.$$.deleteScheduled = false;
                return clone2;
              }
            },
            "delete"() {
              if (!this.$$.ptr) {
                throwInstanceAlreadyDeleted(this);
              }
              if (this.$$.deleteScheduled && !this.$$.preservePointerOnDelete) {
                throwBindingError("Object already scheduled for deletion");
              }
              detachFinalizer(this);
              releaseClassHandle(this.$$);
              if (!this.$$.preservePointerOnDelete) {
                this.$$.smartPtr = void 0;
                this.$$.ptr = void 0;
              }
            },
            "isDeleted"() {
              return !this.$$.ptr;
            },
            "deleteLater"() {
              if (!this.$$.ptr) {
                throwInstanceAlreadyDeleted(this);
              }
              if (this.$$.deleteScheduled && !this.$$.preservePointerOnDelete) {
                throwBindingError("Object already scheduled for deletion");
              }
              this.$$.deleteScheduled = true;
              return this;
            }
          });
          const symbolDispose = Symbol.dispose;
          if (symbolDispose) {
            proto[symbolDispose] = proto["delete"];
          }
        };
        function ClassHandle() {
        }
        var createNamedFunction = (name2, func) => Object.defineProperty(func, "name", { value: name2 });
        var ensureOverloadTable = (proto, methodName, humanName) => {
          if (void 0 === proto[methodName].overloadTable) {
            var prevFunc = proto[methodName];
            proto[methodName] = function(...args) {
              if (!proto[methodName].overloadTable.hasOwnProperty(args.length)) {
                throwBindingError(`Function '${humanName}' called with an invalid number of arguments (${args.length}) - expects one of (${proto[methodName].overloadTable})!`);
              }
              return proto[methodName].overloadTable[args.length].apply(this, args);
            };
            proto[methodName].overloadTable = [];
            proto[methodName].overloadTable[prevFunc.argCount] = prevFunc;
          }
        };
        var exposePublicSymbol = (name2, value, numArguments) => {
          if (Module.hasOwnProperty(name2)) {
            if (void 0 === numArguments || void 0 !== Module[name2].overloadTable && void 0 !== Module[name2].overloadTable[numArguments]) {
              throwBindingError(`Cannot register public name '${name2}' twice`);
            }
            ensureOverloadTable(Module, name2, name2);
            if (Module[name2].overloadTable.hasOwnProperty(numArguments)) {
              throwBindingError(`Cannot register multiple overloads of a function with the same number of arguments (${numArguments})!`);
            }
            Module[name2].overloadTable[numArguments] = value;
          } else {
            Module[name2] = value;
            Module[name2].argCount = numArguments;
          }
        };
        var char_0 = 48;
        var char_9 = 57;
        var makeLegalFunctionName = (name2) => {
          assert2(typeof name2 === "string");
          name2 = name2.replace(/[^a-zA-Z0-9_]/g, "$");
          var f = name2.charCodeAt(0);
          if (f >= char_0 && f <= char_9) {
            return `_${name2}`;
          }
          return name2;
        };
        function RegisteredClass(name2, constructor, instancePrototype, rawDestructor, baseClass, getActualType, upcast, downcast) {
          this.name = name2;
          this.constructor = constructor;
          this.instancePrototype = instancePrototype;
          this.rawDestructor = rawDestructor;
          this.baseClass = baseClass;
          this.getActualType = getActualType;
          this.upcast = upcast;
          this.downcast = downcast;
          this.pureVirtualFunctions = [];
        }
        var upcastPointer = (ptr, ptrClass, desiredClass) => {
          while (ptrClass !== desiredClass) {
            if (!ptrClass.upcast) {
              throwBindingError(`Expected null or instance of ${desiredClass.name}, got an instance of ${ptrClass.name}`);
            }
            ptr = ptrClass.upcast(ptr);
            ptrClass = ptrClass.baseClass;
          }
          return ptr;
        };
        function constNoSmartPtrRawPointerToWireType(destructors, handle) {
          if (handle === null) {
            if (this.isReference) {
              throwBindingError(`null is not a valid ${this.name}`);
            }
            return 0;
          }
          if (!handle.$$) {
            throwBindingError(`Cannot pass "${embindRepr(handle)}" as a ${this.name}`);
          }
          if (!handle.$$.ptr) {
            throwBindingError(`Cannot pass deleted object as a pointer of type ${this.name}`);
          }
          var handleClass = handle.$$.ptrType.registeredClass;
          var ptr = upcastPointer(handle.$$.ptr, handleClass, this.registeredClass);
          return ptr;
        }
        function genericPointerToWireType(destructors, handle) {
          var ptr;
          if (handle === null) {
            if (this.isReference) {
              throwBindingError(`null is not a valid ${this.name}`);
            }
            if (this.isSmartPointer) {
              ptr = this.rawConstructor();
              if (destructors !== null) {
                destructors.push(this.rawDestructor, ptr);
              }
              return ptr;
            } else {
              return 0;
            }
          }
          if (!handle || !handle.$$) {
            throwBindingError(`Cannot pass "${embindRepr(handle)}" as a ${this.name}`);
          }
          if (!handle.$$.ptr) {
            throwBindingError(`Cannot pass deleted object as a pointer of type ${this.name}`);
          }
          if (!this.isConst && handle.$$.ptrType.isConst) {
            throwBindingError(`Cannot convert argument of type ${handle.$$.smartPtrType ? handle.$$.smartPtrType.name : handle.$$.ptrType.name} to parameter type ${this.name}`);
          }
          var handleClass = handle.$$.ptrType.registeredClass;
          ptr = upcastPointer(handle.$$.ptr, handleClass, this.registeredClass);
          if (this.isSmartPointer) {
            if (void 0 === handle.$$.smartPtr) {
              throwBindingError("Passing raw pointer to smart pointer is illegal");
            }
            switch (this.sharingPolicy) {
              case 0:
                if (handle.$$.smartPtrType === this) {
                  ptr = handle.$$.smartPtr;
                } else {
                  throwBindingError(`Cannot convert argument of type ${handle.$$.smartPtrType ? handle.$$.smartPtrType.name : handle.$$.ptrType.name} to parameter type ${this.name}`);
                }
                break;
              case 1:
                ptr = handle.$$.smartPtr;
                break;
              case 2:
                if (handle.$$.smartPtrType === this) {
                  ptr = handle.$$.smartPtr;
                } else {
                  var clonedHandle = handle["clone"]();
                  ptr = this.rawShare(
                    ptr,
                    Emval.toHandle(() => clonedHandle["delete"]())
                  );
                  if (destructors !== null) {
                    destructors.push(this.rawDestructor, ptr);
                  }
                }
                break;
              default:
                throwBindingError("Unsupporting sharing policy");
            }
          }
          return ptr;
        }
        function nonConstNoSmartPtrRawPointerToWireType(destructors, handle) {
          if (handle === null) {
            if (this.isReference) {
              throwBindingError(`null is not a valid ${this.name}`);
            }
            return 0;
          }
          if (!handle.$$) {
            throwBindingError(`Cannot pass "${embindRepr(handle)}" as a ${this.name}`);
          }
          if (!handle.$$.ptr) {
            throwBindingError(`Cannot pass deleted object as a pointer of type ${this.name}`);
          }
          if (handle.$$.ptrType.isConst) {
            throwBindingError(`Cannot convert argument of type ${handle.$$.ptrType.name} to parameter type ${this.name}`);
          }
          var handleClass = handle.$$.ptrType.registeredClass;
          var ptr = upcastPointer(handle.$$.ptr, handleClass, this.registeredClass);
          return ptr;
        }
        function readPointer(pointer) {
          return this["fromWireType"](HEAPU32[pointer >> 2]);
        }
        var init_RegisteredPointer = () => {
          Object.assign(RegisteredPointer.prototype, {
            getPointee(ptr) {
              if (this.rawGetPointee) {
                ptr = this.rawGetPointee(ptr);
              }
              return ptr;
            },
            destructor(ptr) {
              var _a3;
              (_a3 = this.rawDestructor) == null ? void 0 : _a3.call(this, ptr);
            },
            argPackAdvance: GenericWireTypeSize,
            "readValueFromPointer": readPointer,
            "fromWireType": RegisteredPointer_fromWireType
          });
        };
        function RegisteredPointer(name2, registeredClass, isReference, isConst, isSmartPointer, pointeeType, sharingPolicy, rawGetPointee, rawConstructor, rawShare, rawDestructor) {
          this.name = name2;
          this.registeredClass = registeredClass;
          this.isReference = isReference;
          this.isConst = isConst;
          this.isSmartPointer = isSmartPointer;
          this.pointeeType = pointeeType;
          this.sharingPolicy = sharingPolicy;
          this.rawGetPointee = rawGetPointee;
          this.rawConstructor = rawConstructor;
          this.rawShare = rawShare;
          this.rawDestructor = rawDestructor;
          if (!isSmartPointer && registeredClass.baseClass === void 0) {
            if (isConst) {
              this["toWireType"] = constNoSmartPtrRawPointerToWireType;
              this.destructorFunction = null;
            } else {
              this["toWireType"] = nonConstNoSmartPtrRawPointerToWireType;
              this.destructorFunction = null;
            }
          } else {
            this["toWireType"] = genericPointerToWireType;
          }
        }
        var replacePublicSymbol = (name2, value, numArguments) => {
          if (!Module.hasOwnProperty(name2)) {
            throwInternalError("Replacing nonexistent public symbol");
          }
          if (void 0 !== Module[name2].overloadTable && void 0 !== numArguments) {
            Module[name2].overloadTable[numArguments] = value;
          } else {
            Module[name2] = value;
            Module[name2].argCount = numArguments;
          }
        };
        var wasmTableMirror = [];
        var wasmTable;
        var getWasmTableEntry = (funcPtr) => {
          var func = wasmTableMirror[funcPtr];
          if (!func) {
            wasmTableMirror[funcPtr] = func = wasmTable.get(funcPtr);
          }
          assert2(wasmTable.get(funcPtr) == func, "JavaScript-side Wasm function table mirror is out of date!");
          return func;
        };
        var embind__requireFunction = (signature, rawFunction, isAsync = false) => {
          assert2(!isAsync, "Async bindings are only supported with JSPI.");
          signature = readLatin1String(signature);
          function makeDynCaller() {
            var rtn = getWasmTableEntry(rawFunction);
            return rtn;
          }
          var fp = makeDynCaller();
          if (typeof fp != "function") {
            throwBindingError(`unknown function pointer with signature ${signature}: ${rawFunction}`);
          }
          return fp;
        };
        class UnboundTypeError extends Error {
        }
        var getTypeName = (type2) => {
          var ptr = ___getTypeName(type2);
          var rv = readLatin1String(ptr);
          _free(ptr);
          return rv;
        };
        var throwUnboundTypeError = (message, types2) => {
          var unboundTypes = [];
          var seen = {};
          function visit(type2) {
            if (seen[type2]) {
              return;
            }
            if (registeredTypes[type2]) {
              return;
            }
            if (typeDependencies[type2]) {
              typeDependencies[type2].forEach(visit);
              return;
            }
            unboundTypes.push(type2);
            seen[type2] = true;
          }
          types2.forEach(visit);
          throw new UnboundTypeError(`${message}: ` + unboundTypes.map(getTypeName).join([", "]));
        };
        var whenDependentTypesAreResolved = (myTypes, dependentTypes, getTypeConverters) => {
          myTypes.forEach((type2) => typeDependencies[type2] = dependentTypes);
          function onComplete(typeConverters2) {
            var myTypeConverters = getTypeConverters(typeConverters2);
            if (myTypeConverters.length !== myTypes.length) {
              throwInternalError("Mismatched type converter count");
            }
            for (var i2 = 0; i2 < myTypes.length; ++i2) {
              registerType(myTypes[i2], myTypeConverters[i2]);
            }
          }
          var typeConverters = new Array(dependentTypes.length);
          var unregisteredTypes = [];
          var registered = 0;
          dependentTypes.forEach((dt, i2) => {
            if (registeredTypes.hasOwnProperty(dt)) {
              typeConverters[i2] = registeredTypes[dt];
            } else {
              unregisteredTypes.push(dt);
              if (!awaitingDependencies.hasOwnProperty(dt)) {
                awaitingDependencies[dt] = [];
              }
              awaitingDependencies[dt].push(() => {
                typeConverters[i2] = registeredTypes[dt];
                ++registered;
                if (registered === unregisteredTypes.length) {
                  onComplete(typeConverters);
                }
              });
            }
          });
          if (0 === unregisteredTypes.length) {
            onComplete(typeConverters);
          }
        };
        var __embind_register_class = (rawType, rawPointerType, rawConstPointerType, baseClassRawType, getActualTypeSignature, getActualType, upcastSignature, upcast, downcastSignature, downcast, name2, destructorSignature, rawDestructor) => {
          name2 = readLatin1String(name2);
          getActualType = embind__requireFunction(getActualTypeSignature, getActualType);
          upcast && (upcast = embind__requireFunction(upcastSignature, upcast));
          downcast && (downcast = embind__requireFunction(downcastSignature, downcast));
          rawDestructor = embind__requireFunction(destructorSignature, rawDestructor);
          var legalFunctionName = makeLegalFunctionName(name2);
          exposePublicSymbol(legalFunctionName, function() {
            throwUnboundTypeError(`Cannot construct ${name2} due to unbound types`, [baseClassRawType]);
          });
          whenDependentTypesAreResolved(
            [rawType, rawPointerType, rawConstPointerType],
            baseClassRawType ? [baseClassRawType] : [],
            (base) => {
              var _a4;
              var _a3;
              base = base[0];
              var baseClass;
              var basePrototype;
              if (baseClassRawType) {
                baseClass = base.registeredClass;
                basePrototype = baseClass.instancePrototype;
              } else {
                basePrototype = ClassHandle.prototype;
              }
              var constructor = createNamedFunction(name2, function(...args) {
                if (Object.getPrototypeOf(this) !== instancePrototype) {
                  throw new BindingError(`Use 'new' to construct ${name2}`);
                }
                if (void 0 === registeredClass.constructor_body) {
                  throw new BindingError(`${name2} has no accessible constructor`);
                }
                var body = registeredClass.constructor_body[args.length];
                if (void 0 === body) {
                  throw new BindingError(`Tried to invoke ctor of ${name2} with invalid number of parameters (${args.length}) - expected (${Object.keys(registeredClass.constructor_body).toString()}) parameters instead!`);
                }
                return body.apply(this, args);
              });
              var instancePrototype = Object.create(basePrototype, {
                constructor: { value: constructor }
              });
              constructor.prototype = instancePrototype;
              var registeredClass = new RegisteredClass(
                name2,
                constructor,
                instancePrototype,
                rawDestructor,
                baseClass,
                getActualType,
                upcast,
                downcast
              );
              if (registeredClass.baseClass) {
                (_a4 = (_a3 = registeredClass.baseClass).__derivedClasses) != null ? _a4 : _a3.__derivedClasses = [];
                registeredClass.baseClass.__derivedClasses.push(registeredClass);
              }
              var referenceConverter = new RegisteredPointer(
                name2,
                registeredClass,
                true,
                false,
                false
              );
              var pointerConverter = new RegisteredPointer(
                name2 + "*",
                registeredClass,
                false,
                false,
                false
              );
              var constPointerConverter = new RegisteredPointer(
                name2 + " const*",
                registeredClass,
                false,
                true,
                false
              );
              registeredPointers[rawType] = {
                pointerType: pointerConverter,
                constPointerType: constPointerConverter
              };
              replacePublicSymbol(legalFunctionName, constructor);
              return [referenceConverter, pointerConverter, constPointerConverter];
            }
          );
        };
        var runDestructors = (destructors) => {
          while (destructors.length) {
            var ptr = destructors.pop();
            var del = destructors.pop();
            del(ptr);
          }
        };
        function usesDestructorStack(argTypes) {
          for (var i2 = 1; i2 < argTypes.length; ++i2) {
            if (argTypes[i2] !== null && argTypes[i2].destructorFunction === void 0) {
              return true;
            }
          }
          return false;
        }
        function getRequiredArgCount(argTypes) {
          var requiredArgCount = argTypes.length - 2;
          for (var i2 = argTypes.length - 1; i2 >= 2; --i2) {
            if (!argTypes[i2].optional) {
              break;
            }
            requiredArgCount--;
          }
          return requiredArgCount;
        }
        function checkArgCount(numArgs, minArgs, maxArgs, humanName, throwBindingError2) {
          if (numArgs < minArgs || numArgs > maxArgs) {
            var argCountMessage = minArgs == maxArgs ? minArgs : `${minArgs} to ${maxArgs}`;
            throwBindingError2(`function ${humanName} called with ${numArgs} arguments, expected ${argCountMessage}`);
          }
        }
        function craftInvokerFunction(humanName, argTypes, classType, cppInvokerFunc, cppTargetFunc, isAsync) {
          var argCount = argTypes.length;
          if (argCount < 2) {
            throwBindingError("argTypes array size mismatch! Must at least get return value and 'this' types!");
          }
          assert2(!isAsync, "Async bindings are only supported with JSPI.");
          var isClassMethodFunc = argTypes[1] !== null && classType !== null;
          var needsDestructorStack = usesDestructorStack(argTypes);
          var returns = argTypes[0].name !== "void";
          var expectedArgCount = argCount - 2;
          var minArgs = getRequiredArgCount(argTypes);
          var argsWired = new Array(expectedArgCount);
          var invokerFuncArgs = [];
          var destructors = [];
          var invokerFn = function(...args) {
            checkArgCount(args.length, minArgs, expectedArgCount, humanName, throwBindingError);
            destructors.length = 0;
            var thisWired;
            invokerFuncArgs.length = isClassMethodFunc ? 2 : 1;
            invokerFuncArgs[0] = cppTargetFunc;
            if (isClassMethodFunc) {
              thisWired = argTypes[1]["toWireType"](destructors, this);
              invokerFuncArgs[1] = thisWired;
            }
            for (var i2 = 0; i2 < expectedArgCount; ++i2) {
              argsWired[i2] = argTypes[i2 + 2]["toWireType"](destructors, args[i2]);
              invokerFuncArgs.push(argsWired[i2]);
            }
            var rv = cppInvokerFunc(...invokerFuncArgs);
            function onDone(rv2) {
              if (needsDestructorStack) {
                runDestructors(destructors);
              } else {
                for (var i22 = isClassMethodFunc ? 1 : 2; i22 < argTypes.length; i22++) {
                  var param = i22 === 1 ? thisWired : argsWired[i22 - 2];
                  if (argTypes[i22].destructorFunction !== null) {
                    argTypes[i22].destructorFunction(param);
                  }
                }
              }
              if (returns) {
                return argTypes[0]["fromWireType"](rv2);
              }
            }
            return onDone(rv);
          };
          return createNamedFunction(humanName, invokerFn);
        }
        var heap32VectorToArray = (count, firstElement) => {
          var array2 = [];
          for (var i2 = 0; i2 < count; i2++) {
            array2.push(HEAPU32[firstElement + i2 * 4 >> 2]);
          }
          return array2;
        };
        var getFunctionName = (signature) => {
          signature = signature.trim();
          const argsIndex = signature.indexOf("(");
          if (argsIndex === -1)
            return signature;
          assert2(signature.endsWith(")"), "Parentheses for argument names should match.");
          return signature.slice(0, argsIndex);
        };
        var __embind_register_class_class_function = (rawClassType, methodName, argCount, rawArgTypesAddr, invokerSignature, rawInvoker, fn, isAsync, isNonnullReturn) => {
          var rawArgTypes = heap32VectorToArray(argCount, rawArgTypesAddr);
          methodName = readLatin1String(methodName);
          methodName = getFunctionName(methodName);
          rawInvoker = embind__requireFunction(invokerSignature, rawInvoker, isAsync);
          whenDependentTypesAreResolved([], [rawClassType], (classType) => {
            classType = classType[0];
            var humanName = `${classType.name}.${methodName}`;
            function unboundTypesHandler() {
              throwUnboundTypeError(`Cannot call ${humanName} due to unbound types`, rawArgTypes);
            }
            if (methodName.startsWith("@@")) {
              methodName = Symbol[methodName.substring(2)];
            }
            var proto = classType.registeredClass.constructor;
            if (void 0 === proto[methodName]) {
              unboundTypesHandler.argCount = argCount - 1;
              proto[methodName] = unboundTypesHandler;
            } else {
              ensureOverloadTable(proto, methodName, humanName);
              proto[methodName].overloadTable[argCount - 1] = unboundTypesHandler;
            }
            whenDependentTypesAreResolved([], rawArgTypes, (argTypes) => {
              var invokerArgsArray = [
                argTypes[0],
                null
                /* no class 'this'*/
              ].concat(
                argTypes.slice(1)
                /* actual params */
              );
              var func = craftInvokerFunction(humanName, invokerArgsArray, null, rawInvoker, fn, isAsync);
              if (void 0 === proto[methodName].overloadTable) {
                func.argCount = argCount - 1;
                proto[methodName] = func;
              } else {
                proto[methodName].overloadTable[argCount - 1] = func;
              }
              if (classType.registeredClass.__derivedClasses) {
                for (const derivedClass of classType.registeredClass.__derivedClasses) {
                  if (!derivedClass.constructor.hasOwnProperty(methodName)) {
                    derivedClass.constructor[methodName] = func;
                  }
                }
              }
              return [];
            });
            return [];
          });
        };
        var __embind_register_class_constructor = (rawClassType, argCount, rawArgTypesAddr, invokerSignature, invoker, rawConstructor) => {
          assert2(argCount > 0);
          var rawArgTypes = heap32VectorToArray(argCount, rawArgTypesAddr);
          invoker = embind__requireFunction(invokerSignature, invoker);
          whenDependentTypesAreResolved([], [rawClassType], (classType) => {
            classType = classType[0];
            var humanName = `constructor ${classType.name}`;
            if (void 0 === classType.registeredClass.constructor_body) {
              classType.registeredClass.constructor_body = [];
            }
            if (void 0 !== classType.registeredClass.constructor_body[argCount - 1]) {
              throw new BindingError(`Cannot register multiple constructors with identical number of parameters (${argCount - 1}) for class '${classType.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`);
            }
            classType.registeredClass.constructor_body[argCount - 1] = () => {
              throwUnboundTypeError(`Cannot construct ${classType.name} due to unbound types`, rawArgTypes);
            };
            whenDependentTypesAreResolved([], rawArgTypes, (argTypes) => {
              argTypes.splice(1, 0, null);
              classType.registeredClass.constructor_body[argCount - 1] = craftInvokerFunction(humanName, argTypes, null, invoker, rawConstructor);
              return [];
            });
            return [];
          });
        };
        var __embind_register_class_function = (rawClassType, methodName, argCount, rawArgTypesAddr, invokerSignature, rawInvoker, context, isPureVirtual, isAsync, isNonnullReturn) => {
          var rawArgTypes = heap32VectorToArray(argCount, rawArgTypesAddr);
          methodName = readLatin1String(methodName);
          methodName = getFunctionName(methodName);
          rawInvoker = embind__requireFunction(invokerSignature, rawInvoker, isAsync);
          whenDependentTypesAreResolved([], [rawClassType], (classType) => {
            classType = classType[0];
            var humanName = `${classType.name}.${methodName}`;
            if (methodName.startsWith("@@")) {
              methodName = Symbol[methodName.substring(2)];
            }
            if (isPureVirtual) {
              classType.registeredClass.pureVirtualFunctions.push(methodName);
            }
            function unboundTypesHandler() {
              throwUnboundTypeError(`Cannot call ${humanName} due to unbound types`, rawArgTypes);
            }
            var proto = classType.registeredClass.instancePrototype;
            var method = proto[methodName];
            if (void 0 === method || void 0 === method.overloadTable && method.className !== classType.name && method.argCount === argCount - 2) {
              unboundTypesHandler.argCount = argCount - 2;
              unboundTypesHandler.className = classType.name;
              proto[methodName] = unboundTypesHandler;
            } else {
              ensureOverloadTable(proto, methodName, humanName);
              proto[methodName].overloadTable[argCount - 2] = unboundTypesHandler;
            }
            whenDependentTypesAreResolved([], rawArgTypes, (argTypes) => {
              var memberFunction = craftInvokerFunction(humanName, argTypes, classType, rawInvoker, context, isAsync);
              if (void 0 === proto[methodName].overloadTable) {
                memberFunction.argCount = argCount - 2;
                proto[methodName] = memberFunction;
              } else {
                proto[methodName].overloadTable[argCount - 2] = memberFunction;
              }
              return [];
            });
            return [];
          });
        };
        var emval_freelist = [];
        var emval_handles = [0, 1, , 1, null, 1, true, 1, false, 1];
        var __emval_decref = (handle) => {
          if (handle > 9 && 0 === --emval_handles[handle + 1]) {
            assert2(emval_handles[handle] !== void 0, `Decref for unallocated handle.`);
            emval_handles[handle] = void 0;
            emval_freelist.push(handle);
          }
        };
        var Emval = {
          toValue: (handle) => {
            if (!handle) {
              throwBindingError(`Cannot use deleted val. handle = ${handle}`);
            }
            assert2(handle === 2 || emval_handles[handle] !== void 0 && handle % 2 === 0, `invalid handle: ${handle}`);
            return emval_handles[handle];
          },
          toHandle: (value) => {
            switch (value) {
              case void 0:
                return 2;
              case null:
                return 4;
              case true:
                return 6;
              case false:
                return 8;
              default: {
                const handle = emval_freelist.pop() || emval_handles.length;
                emval_handles[handle] = value;
                emval_handles[handle + 1] = 1;
                return handle;
              }
            }
          }
        };
        var EmValType = {
          name: "emscripten::val",
          "fromWireType": (handle) => {
            var rv = Emval.toValue(handle);
            __emval_decref(handle);
            return rv;
          },
          "toWireType": (destructors, value) => Emval.toHandle(value),
          argPackAdvance: GenericWireTypeSize,
          "readValueFromPointer": readPointer,
          destructorFunction: null
          // This type does not need a destructor
          // TODO: do we need a deleteObject here?  write a test where
          // emval is passed into JS via an interface
        };
        var __embind_register_emval = (rawType) => registerType(rawType, EmValType);
        var floatReadValueFromPointer = (name2, width) => {
          switch (width) {
            case 4:
              return function(pointer) {
                return this["fromWireType"](HEAPF32[pointer >> 2]);
              };
            case 8:
              return function(pointer) {
                return this["fromWireType"](HEAPF64[pointer >> 3]);
              };
            default:
              throw new TypeError(`invalid float width (${width}): ${name2}`);
          }
        };
        var __embind_register_float = (rawType, name2, size) => {
          name2 = readLatin1String(name2);
          registerType(rawType, {
            name: name2,
            "fromWireType": (value) => value,
            "toWireType": (destructors, value) => {
              if (typeof value != "number" && typeof value != "boolean") {
                throw new TypeError(`Cannot convert ${embindRepr(value)} to ${this.name}`);
              }
              return value;
            },
            argPackAdvance: GenericWireTypeSize,
            "readValueFromPointer": floatReadValueFromPointer(name2, size),
            destructorFunction: null
            // This type does not need a destructor
          });
        };
        var __embind_register_function = (name2, argCount, rawArgTypesAddr, signature, rawInvoker, fn, isAsync, isNonnullReturn) => {
          var argTypes = heap32VectorToArray(argCount, rawArgTypesAddr);
          name2 = readLatin1String(name2);
          name2 = getFunctionName(name2);
          rawInvoker = embind__requireFunction(signature, rawInvoker, isAsync);
          exposePublicSymbol(name2, function() {
            throwUnboundTypeError(`Cannot call ${name2} due to unbound types`, argTypes);
          }, argCount - 1);
          whenDependentTypesAreResolved([], argTypes, (argTypes2) => {
            var invokerArgsArray = [
              argTypes2[0],
              null
              /* no class 'this'*/
            ].concat(
              argTypes2.slice(1)
              /* actual params */
            );
            replacePublicSymbol(name2, craftInvokerFunction(name2, invokerArgsArray, null, rawInvoker, fn, isAsync), argCount - 1);
            return [];
          });
        };
        var __embind_register_integer = (primitiveType, name2, size, minRange, maxRange) => {
          name2 = readLatin1String(name2);
          const isUnsignedType = minRange === 0;
          let fromWireType = (value) => value;
          if (isUnsignedType) {
            var bitshift = 32 - 8 * size;
            fromWireType = (value) => value << bitshift >>> bitshift;
            maxRange = fromWireType(maxRange);
          }
          registerType(primitiveType, {
            name: name2,
            "fromWireType": fromWireType,
            "toWireType": (destructors, value) => {
              if (typeof value != "number" && typeof value != "boolean") {
                throw new TypeError(`Cannot convert "${embindRepr(value)}" to ${name2}`);
              }
              assertIntegerRange(name2, value, minRange, maxRange);
              return value;
            },
            argPackAdvance: GenericWireTypeSize,
            "readValueFromPointer": integerReadValueFromPointer(name2, size, minRange !== 0),
            destructorFunction: null
            // This type does not need a destructor
          });
        };
        var __embind_register_memory_view = (rawType, dataTypeIndex, name2) => {
          var typeMapping = [
            Int8Array,
            Uint8Array,
            Int16Array,
            Uint16Array,
            Int32Array,
            Uint32Array,
            Float32Array,
            Float64Array,
            BigInt64Array,
            BigUint64Array
          ];
          var TA = typeMapping[dataTypeIndex];
          function decodeMemoryView(handle) {
            var size = HEAPU32[handle >> 2];
            var data = HEAPU32[handle + 4 >> 2];
            return new TA(HEAP8.buffer, data, size);
          }
          name2 = readLatin1String(name2);
          registerType(rawType, {
            name: name2,
            "fromWireType": decodeMemoryView,
            argPackAdvance: GenericWireTypeSize,
            "readValueFromPointer": decodeMemoryView
          }, {
            ignoreDuplicateRegistrations: true
          });
        };
        var EmValOptionalType = Object.assign({ optional: true }, EmValType);
        var __embind_register_optional = (rawOptionalType, rawType) => {
          registerType(rawOptionalType, EmValOptionalType);
        };
        var stringToUTF8 = (str, outPtr, maxBytesToWrite) => {
          assert2(typeof maxBytesToWrite == "number", "stringToUTF8(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!");
          return stringToUTF8Array(str, HEAPU8, outPtr, maxBytesToWrite);
        };
        var __embind_register_std_string = (rawType, name2) => {
          name2 = readLatin1String(name2);
          registerType(rawType, {
            name: name2,
            // For some method names we use string keys here since they are part of
            // the public/external API and/or used by the runtime-generated code.
            "fromWireType"(value) {
              var length = HEAPU32[value >> 2];
              var payload = value + 4;
              var str;
              var i2;
              {
                var decodeStartPtr = payload;
                for (var i2 = 0; i2 <= length; ++i2) {
                  var currentBytePtr = payload + i2;
                  if (i2 == length || HEAPU8[currentBytePtr] == 0) {
                    var maxRead = currentBytePtr - decodeStartPtr;
                    var stringSegment = UTF8ToString(decodeStartPtr, maxRead);
                    if (str === void 0) {
                      str = stringSegment;
                    } else {
                      str += String.fromCharCode(0);
                      str += stringSegment;
                    }
                    decodeStartPtr = currentBytePtr + 1;
                  }
                }
              }
              _free(value);
              return str;
            },
            "toWireType"(destructors, value) {
              if (value instanceof ArrayBuffer) {
                value = new Uint8Array(value);
              }
              var length;
              var valueIsOfTypeString = typeof value == "string";
              if (!(valueIsOfTypeString || ArrayBuffer.isView(value) && value.BYTES_PER_ELEMENT == 1)) {
                throwBindingError("Cannot pass non-string to std::string");
              }
              if (valueIsOfTypeString) {
                length = lengthBytesUTF8(value);
              } else {
                length = value.length;
              }
              var base = _malloc(4 + length + 1);
              var ptr = base + 4;
              HEAPU32[base >> 2] = length;
              if (valueIsOfTypeString) {
                {
                  stringToUTF8(value, ptr, length + 1);
                }
              } else {
                HEAPU8.set(value, ptr);
              }
              if (destructors !== null) {
                destructors.push(_free, base);
              }
              return base;
            },
            argPackAdvance: GenericWireTypeSize,
            "readValueFromPointer": readPointer,
            destructorFunction(ptr) {
              _free(ptr);
            }
          });
        };
        var UTF16Decoder = typeof TextDecoder != "undefined" ? new TextDecoder("utf-16le") : void 0;
        var UTF16ToString = (ptr, maxBytesToRead) => {
          assert2(ptr % 2 == 0, "Pointer passed to UTF16ToString must be aligned to two bytes!");
          var idx = ptr >> 1;
          var maxIdx = idx + maxBytesToRead / 2;
          var endIdx = idx;
          while (!(endIdx >= maxIdx) && HEAPU16[endIdx])
            ++endIdx;
          if (endIdx - idx > 16 && UTF16Decoder)
            return UTF16Decoder.decode(HEAPU16.subarray(idx, endIdx));
          var str = "";
          for (var i2 = idx; !(i2 >= maxIdx); ++i2) {
            var codeUnit = HEAPU16[i2];
            if (codeUnit == 0)
              break;
            str += String.fromCharCode(codeUnit);
          }
          return str;
        };
        var stringToUTF16 = (str, outPtr, maxBytesToWrite) => {
          assert2(outPtr % 2 == 0, "Pointer passed to stringToUTF16 must be aligned to two bytes!");
          assert2(typeof maxBytesToWrite == "number", "stringToUTF16(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!");
          maxBytesToWrite != null ? maxBytesToWrite : maxBytesToWrite = 2147483647;
          if (maxBytesToWrite < 2)
            return 0;
          maxBytesToWrite -= 2;
          var startPtr = outPtr;
          var numCharsToWrite = maxBytesToWrite < str.length * 2 ? maxBytesToWrite / 2 : str.length;
          for (var i2 = 0; i2 < numCharsToWrite; ++i2) {
            var codeUnit = str.charCodeAt(i2);
            HEAP16[outPtr >> 1] = codeUnit;
            outPtr += 2;
          }
          HEAP16[outPtr >> 1] = 0;
          return outPtr - startPtr;
        };
        var lengthBytesUTF16 = (str) => str.length * 2;
        var UTF32ToString = (ptr, maxBytesToRead) => {
          assert2(ptr % 4 == 0, "Pointer passed to UTF32ToString must be aligned to four bytes!");
          var i2 = 0;
          var str = "";
          while (!(i2 >= maxBytesToRead / 4)) {
            var utf32 = HEAP32[ptr + i2 * 4 >> 2];
            if (utf32 == 0)
              break;
            ++i2;
            if (utf32 >= 65536) {
              var ch = utf32 - 65536;
              str += String.fromCharCode(55296 | ch >> 10, 56320 | ch & 1023);
            } else {
              str += String.fromCharCode(utf32);
            }
          }
          return str;
        };
        var stringToUTF32 = (str, outPtr, maxBytesToWrite) => {
          assert2(outPtr % 4 == 0, "Pointer passed to stringToUTF32 must be aligned to four bytes!");
          assert2(typeof maxBytesToWrite == "number", "stringToUTF32(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!");
          maxBytesToWrite != null ? maxBytesToWrite : maxBytesToWrite = 2147483647;
          if (maxBytesToWrite < 4)
            return 0;
          var startPtr = outPtr;
          var endPtr = startPtr + maxBytesToWrite - 4;
          for (var i2 = 0; i2 < str.length; ++i2) {
            var codeUnit = str.charCodeAt(i2);
            if (codeUnit >= 55296 && codeUnit <= 57343) {
              var trailSurrogate = str.charCodeAt(++i2);
              codeUnit = 65536 + ((codeUnit & 1023) << 10) | trailSurrogate & 1023;
            }
            HEAP32[outPtr >> 2] = codeUnit;
            outPtr += 4;
            if (outPtr + 4 > endPtr)
              break;
          }
          HEAP32[outPtr >> 2] = 0;
          return outPtr - startPtr;
        };
        var lengthBytesUTF32 = (str) => {
          var len2 = 0;
          for (var i2 = 0; i2 < str.length; ++i2) {
            var codeUnit = str.charCodeAt(i2);
            if (codeUnit >= 55296 && codeUnit <= 57343)
              ++i2;
            len2 += 4;
          }
          return len2;
        };
        var __embind_register_std_wstring = (rawType, charSize, name2) => {
          name2 = readLatin1String(name2);
          var decodeString, encodeString, readCharAt, lengthBytesUTF;
          if (charSize === 2) {
            decodeString = UTF16ToString;
            encodeString = stringToUTF16;
            lengthBytesUTF = lengthBytesUTF16;
            readCharAt = (pointer) => HEAPU16[pointer >> 1];
          } else if (charSize === 4) {
            decodeString = UTF32ToString;
            encodeString = stringToUTF32;
            lengthBytesUTF = lengthBytesUTF32;
            readCharAt = (pointer) => HEAPU32[pointer >> 2];
          }
          registerType(rawType, {
            name: name2,
            "fromWireType": (value) => {
              var length = HEAPU32[value >> 2];
              var str;
              var decodeStartPtr = value + 4;
              for (var i2 = 0; i2 <= length; ++i2) {
                var currentBytePtr = value + 4 + i2 * charSize;
                if (i2 == length || readCharAt(currentBytePtr) == 0) {
                  var maxReadBytes = currentBytePtr - decodeStartPtr;
                  var stringSegment = decodeString(decodeStartPtr, maxReadBytes);
                  if (str === void 0) {
                    str = stringSegment;
                  } else {
                    str += String.fromCharCode(0);
                    str += stringSegment;
                  }
                  decodeStartPtr = currentBytePtr + charSize;
                }
              }
              _free(value);
              return str;
            },
            "toWireType": (destructors, value) => {
              if (!(typeof value == "string")) {
                throwBindingError(`Cannot pass non-string to C++ string type ${name2}`);
              }
              var length = lengthBytesUTF(value);
              var ptr = _malloc(4 + length + charSize);
              HEAPU32[ptr >> 2] = length / charSize;
              encodeString(value, ptr + 4, length + charSize);
              if (destructors !== null) {
                destructors.push(_free, ptr);
              }
              return ptr;
            },
            argPackAdvance: GenericWireTypeSize,
            "readValueFromPointer": readPointer,
            destructorFunction(ptr) {
              _free(ptr);
            }
          });
        };
        var __embind_register_void = (rawType, name2) => {
          name2 = readLatin1String(name2);
          registerType(rawType, {
            isVoid: true,
            // void return values can be optimized out sometimes
            name: name2,
            argPackAdvance: 0,
            "fromWireType": () => void 0,
            // TODO: assert if anything else is given?
            "toWireType": (destructors, o) => void 0
          });
        };
        var emval_symbols = {};
        var getStringOrSymbol = (address) => {
          var symbol2 = emval_symbols[address];
          if (symbol2 === void 0) {
            return readLatin1String(address);
          }
          return symbol2;
        };
        var emval_methodCallers = [];
        var __emval_call_method = (caller, objHandle, methodName, destructorsRef, args) => {
          caller = emval_methodCallers[caller];
          objHandle = Emval.toValue(objHandle);
          methodName = getStringOrSymbol(methodName);
          return caller(objHandle, objHandle[methodName], destructorsRef, args);
        };
        var emval_addMethodCaller = (caller) => {
          var id2 = emval_methodCallers.length;
          emval_methodCallers.push(caller);
          return id2;
        };
        var requireRegisteredType = (rawType, humanName) => {
          var impl = registeredTypes[rawType];
          if (void 0 === impl) {
            throwBindingError(`${humanName} has unknown type ${getTypeName(rawType)}`);
          }
          return impl;
        };
        var emval_lookupTypes = (argCount, argTypes) => {
          var a = new Array(argCount);
          for (var i2 = 0; i2 < argCount; ++i2) {
            a[i2] = requireRegisteredType(
              HEAPU32[argTypes + i2 * 4 >> 2],
              `parameter ${i2}`
            );
          }
          return a;
        };
        var emval_returnValue = (returnType, destructorsRef, handle) => {
          var destructors = [];
          var result2 = returnType["toWireType"](destructors, handle);
          if (destructors.length) {
            HEAPU32[destructorsRef >> 2] = Emval.toHandle(destructors);
          }
          return result2;
        };
        var reflectConstruct = Reflect.construct;
        var __emval_get_method_caller = (argCount, argTypes, kind) => {
          var types2 = emval_lookupTypes(argCount, argTypes);
          var retType = types2.shift();
          argCount--;
          var argN = new Array(argCount);
          var invokerFunction = (obj, func, destructorsRef, args) => {
            var offset = 0;
            for (var i2 = 0; i2 < argCount; ++i2) {
              argN[i2] = types2[i2]["readValueFromPointer"](args + offset);
              offset += types2[i2].argPackAdvance;
            }
            var rv = kind === /* CONSTRUCTOR */
            1 ? reflectConstruct(func, argN) : func.apply(obj, argN);
            return emval_returnValue(retType, destructorsRef, rv);
          };
          var functionName = `methodCaller<(${types2.map((t) => t.name).join(", ")}) => ${retType.name}>`;
          return emval_addMethodCaller(createNamedFunction(functionName, invokerFunction));
        };
        var __emval_incref = (handle) => {
          if (handle > 9) {
            emval_handles[handle + 1] += 1;
          }
        };
        var __emval_new_array = () => Emval.toHandle([]);
        var __emval_new_cstring = (v) => Emval.toHandle(getStringOrSymbol(v));
        var __emval_new_object = () => Emval.toHandle({});
        var __emval_run_destructors = (handle) => {
          var destructors = Emval.toValue(handle);
          runDestructors(destructors);
          __emval_decref(handle);
        };
        var __emval_set_property = (handle, key, value) => {
          handle = Emval.toValue(handle);
          key = Emval.toValue(key);
          value = Emval.toValue(value);
          handle[key] = value;
        };
        var __emval_take_value = (type2, arg) => {
          type2 = requireRegisteredType(type2, "_emval_take_value");
          var v = type2["readValueFromPointer"](arg);
          return Emval.toHandle(v);
        };
        var __tzset_js = (timezone, daylight, std_name, dst_name) => {
          var currentYear = (/* @__PURE__ */ new Date()).getFullYear();
          var winter = new Date(currentYear, 0, 1);
          var summer = new Date(currentYear, 6, 1);
          var winterOffset = winter.getTimezoneOffset();
          var summerOffset = summer.getTimezoneOffset();
          var stdTimezoneOffset = Math.max(winterOffset, summerOffset);
          HEAPU32[timezone >> 2] = stdTimezoneOffset * 60;
          HEAP32[daylight >> 2] = Number(winterOffset != summerOffset);
          var extractZone = (timezoneOffset) => {
            var sign = timezoneOffset >= 0 ? "-" : "+";
            var absOffset = Math.abs(timezoneOffset);
            var hours = String(Math.floor(absOffset / 60)).padStart(2, "0");
            var minutes = String(absOffset % 60).padStart(2, "0");
            return `UTC${sign}${hours}${minutes}`;
          };
          var winterName = extractZone(winterOffset);
          var summerName = extractZone(summerOffset);
          assert2(winterName);
          assert2(summerName);
          assert2(lengthBytesUTF8(winterName) <= 16, `timezone name truncated to fit in TZNAME_MAX (${winterName})`);
          assert2(lengthBytesUTF8(summerName) <= 16, `timezone name truncated to fit in TZNAME_MAX (${summerName})`);
          if (summerOffset < winterOffset) {
            stringToUTF8(winterName, std_name, 17);
            stringToUTF8(summerName, dst_name, 17);
          } else {
            stringToUTF8(winterName, dst_name, 17);
            stringToUTF8(summerName, std_name, 17);
          }
        };
        var readEmAsmArgsArray = [];
        var readEmAsmArgs = (sigPtr, buf) => {
          assert2(Array.isArray(readEmAsmArgsArray));
          assert2(buf % 16 == 0);
          readEmAsmArgsArray.length = 0;
          var ch;
          while (ch = HEAPU8[sigPtr++]) {
            var chr = String.fromCharCode(ch);
            var validChars = ["d", "f", "i", "p"];
            validChars.push("j");
            assert2(validChars.includes(chr), `Invalid character ${ch}("${chr}") in readEmAsmArgs! Use only [${validChars}], and do not specify "v" for void return argument.`);
            var wide = ch != 105;
            wide &= ch != 112;
            buf += wide && buf % 8 ? 4 : 0;
            readEmAsmArgsArray.push(
              // Special case for pointers under wasm64 or CAN_ADDRESS_2GB mode.
              ch == 112 ? HEAPU32[buf >> 2] : ch == 106 ? HEAP64[buf >> 3] : ch == 105 ? HEAP32[buf >> 2] : HEAPF64[buf >> 3]
            );
            buf += wide ? 8 : 4;
          }
          return readEmAsmArgsArray;
        };
        var runEmAsmFunction = (code2, sigPtr, argbuf) => {
          var args = readEmAsmArgs(sigPtr, argbuf);
          assert2(ASM_CONSTS.hasOwnProperty(code2), `No EM_ASM constant found at address ${code2}.  The loaded WebAssembly file is likely out of sync with the generated JavaScript.`);
          return ASM_CONSTS[code2](...args);
        };
        var _emscripten_asm_const_int = (code2, sigPtr, argbuf) => {
          return runEmAsmFunction(code2, sigPtr, argbuf);
        };
        var getHeapMax = () => (
          // Stay one Wasm page short of 4GB: while e.g. Chrome is able to allocate
          // full 4GB Wasm memories, the size will wrap back to 0 bytes in Wasm side
          // for any code that deals with heap sizes, which would require special
          // casing all heap size related code to treat 0 specially.
          2147483648
        );
        var alignMemory = (size, alignment) => {
          assert2(alignment, "alignment argument is required");
          return Math.ceil(size / alignment) * alignment;
        };
        var growMemory = (size) => {
          var b = wasmMemory.buffer;
          var pages = (size - b.byteLength + 65535) / 65536 | 0;
          try {
            wasmMemory.grow(pages);
            updateMemoryViews();
            return 1;
          } catch (e) {
            err(`growMemory: Attempted to grow heap from ${b.byteLength} bytes to ${size} bytes, but got error: ${e}`);
          }
        };
        var _emscripten_resize_heap = (requestedSize) => {
          var oldSize = HEAPU8.length;
          requestedSize >>>= 0;
          assert2(requestedSize > oldSize);
          var maxHeapSize = getHeapMax();
          if (requestedSize > maxHeapSize) {
            err(`Cannot enlarge memory, requested ${requestedSize} bytes, but the limit is ${maxHeapSize} bytes!`);
            return false;
          }
          for (var cutDown = 1; cutDown <= 4; cutDown *= 2) {
            var overGrownHeapSize = oldSize * (1 + 0.2 / cutDown);
            overGrownHeapSize = Math.min(overGrownHeapSize, requestedSize + 100663296);
            var newSize = Math.min(maxHeapSize, alignMemory(Math.max(requestedSize, overGrownHeapSize), 65536));
            var replacement = growMemory(newSize);
            if (replacement) {
              return true;
            }
          }
          err(`Failed to grow the heap from ${oldSize} bytes to ${newSize} bytes, not enough memory!`);
          return false;
        };
        var ENV = {};
        var getExecutableName = () => thisProgram || "./this.program";
        var getEnvStrings = () => {
          if (!getEnvStrings.strings) {
            var lang = (typeof navigator == "object" && navigator.languages && navigator.languages[0] || "C").replace("-", "_") + ".UTF-8";
            var env2 = {
              "USER": "web_user",
              "LOGNAME": "web_user",
              "PATH": "/",
              "PWD": "/",
              "HOME": "/home/web_user",
              "LANG": lang,
              "_": getExecutableName()
            };
            for (var x in ENV) {
              if (ENV[x] === void 0)
                delete env2[x];
              else
                env2[x] = ENV[x];
            }
            var strings = [];
            for (var x in env2) {
              strings.push(`${x}=${env2[x]}`);
            }
            getEnvStrings.strings = strings;
          }
          return getEnvStrings.strings;
        };
        var _environ_get = (__environ, environ_buf) => {
          var bufSize = 0;
          var envp = 0;
          for (var string2 of getEnvStrings()) {
            var ptr = environ_buf + bufSize;
            HEAPU32[__environ + envp >> 2] = ptr;
            bufSize += stringToUTF8(string2, ptr, Infinity) + 1;
            envp += 4;
          }
          return 0;
        };
        var _environ_sizes_get = (penviron_count, penviron_buf_size) => {
          var strings = getEnvStrings();
          HEAPU32[penviron_count >> 2] = strings.length;
          var bufSize = 0;
          for (var string2 of strings) {
            bufSize += lengthBytesUTF8(string2) + 1;
          }
          HEAPU32[penviron_buf_size >> 2] = bufSize;
          return 0;
        };
        function _fd_close(fd) {
          try {
            var stream = SYSCALLS.getStreamFromFD(fd);
            FS.close(stream);
            return 0;
          } catch (e) {
            if (typeof FS == "undefined" || !(e.name === "ErrnoError"))
              throw e;
            return e.errno;
          }
        }
        var doReadv = (stream, iov, iovcnt, offset) => {
          var ret = 0;
          for (var i2 = 0; i2 < iovcnt; i2++) {
            var ptr = HEAPU32[iov >> 2];
            var len2 = HEAPU32[iov + 4 >> 2];
            iov += 8;
            var curr = FS.read(stream, HEAP8, ptr, len2, offset);
            if (curr < 0)
              return -1;
            ret += curr;
            if (curr < len2)
              break;
          }
          return ret;
        };
        function _fd_read(fd, iov, iovcnt, pnum) {
          try {
            var stream = SYSCALLS.getStreamFromFD(fd);
            var num = doReadv(stream, iov, iovcnt);
            HEAPU32[pnum >> 2] = num;
            return 0;
          } catch (e) {
            if (typeof FS == "undefined" || !(e.name === "ErrnoError"))
              throw e;
            return e.errno;
          }
        }
        var INT53_MAX = 9007199254740992;
        var INT53_MIN = -9007199254740992;
        var bigintToI53Checked = (num) => num < INT53_MIN || num > INT53_MAX ? NaN : Number(num);
        function _fd_seek(fd, offset, whence, newOffset) {
          offset = bigintToI53Checked(offset);
          try {
            if (isNaN(offset))
              return 61;
            var stream = SYSCALLS.getStreamFromFD(fd);
            FS.llseek(stream, offset, whence);
            HEAP64[newOffset >> 3] = BigInt(stream.position);
            if (stream.getdents && offset === 0 && whence === 0)
              stream.getdents = null;
            return 0;
          } catch (e) {
            if (typeof FS == "undefined" || !(e.name === "ErrnoError"))
              throw e;
            return e.errno;
          }
        }
        var doWritev = (stream, iov, iovcnt, offset) => {
          var ret = 0;
          for (var i2 = 0; i2 < iovcnt; i2++) {
            var ptr = HEAPU32[iov >> 2];
            var len2 = HEAPU32[iov + 4 >> 2];
            iov += 8;
            var curr = FS.write(stream, HEAP8, ptr, len2, offset);
            if (curr < 0)
              return -1;
            ret += curr;
            if (curr < len2) {
              break;
            }
          }
          return ret;
        };
        function _fd_write(fd, iov, iovcnt, pnum) {
          try {
            var stream = SYSCALLS.getStreamFromFD(fd);
            var num = doWritev(stream, iov, iovcnt);
            HEAPU32[pnum >> 2] = num;
            return 0;
          } catch (e) {
            if (typeof FS == "undefined" || !(e.name === "ErrnoError"))
              throw e;
            return e.errno;
          }
        }
        var incrementExceptionRefcount = (ex) => {
          var ptr = getCppExceptionThrownObjectFromWebAssemblyException(ex);
          ___cxa_increment_exception_refcount(ptr);
        };
        var decrementExceptionRefcount = (ex) => {
          var ptr = getCppExceptionThrownObjectFromWebAssemblyException(ex);
          ___cxa_decrement_exception_refcount(ptr);
        };
        FS.createPreloadedFile = FS_createPreloadedFile;
        FS.staticInit();
        embind_init_charCodes();
        init_ClassHandle();
        init_RegisteredPointer();
        assert2(emval_handles.length === 5 * 2);
        {
          if (Module["noExitRuntime"])
            Module["noExitRuntime"];
          if (Module["preloadPlugins"])
            preloadPlugins = Module["preloadPlugins"];
          if (Module["print"])
            out = Module["print"];
          if (Module["printErr"])
            err = Module["printErr"];
          if (Module["wasmBinary"])
            wasmBinary = Module["wasmBinary"];
          checkIncomingModuleAPI();
          if (Module["arguments"])
            Module["arguments"];
          if (Module["thisProgram"])
            thisProgram = Module["thisProgram"];
          assert2(typeof Module["memoryInitializerPrefixURL"] == "undefined", "Module.memoryInitializerPrefixURL option was removed, use Module.locateFile instead");
          assert2(typeof Module["pthreadMainPrefixURL"] == "undefined", "Module.pthreadMainPrefixURL option was removed, use Module.locateFile instead");
          assert2(typeof Module["cdInitializerPrefixURL"] == "undefined", "Module.cdInitializerPrefixURL option was removed, use Module.locateFile instead");
          assert2(typeof Module["filePackagePrefixURL"] == "undefined", "Module.filePackagePrefixURL option was removed, use Module.locateFile instead");
          assert2(typeof Module["read"] == "undefined", "Module.read option was removed");
          assert2(typeof Module["readAsync"] == "undefined", "Module.readAsync option was removed (modify readAsync in JS)");
          assert2(typeof Module["readBinary"] == "undefined", "Module.readBinary option was removed (modify readBinary in JS)");
          assert2(typeof Module["setWindowTitle"] == "undefined", "Module.setWindowTitle option was removed (modify emscripten_set_window_title in JS)");
          assert2(typeof Module["TOTAL_MEMORY"] == "undefined", "Module.TOTAL_MEMORY has been renamed Module.INITIAL_MEMORY");
          assert2(typeof Module["ENVIRONMENT"] == "undefined", "Module.ENVIRONMENT has been deprecated. To force the environment, use the ENVIRONMENT compile-time option (for example, -sENVIRONMENT=web or -sENVIRONMENT=node)");
          assert2(typeof Module["STACK_SIZE"] == "undefined", "STACK_SIZE can no longer be set at runtime.  Use -sSTACK_SIZE at link time");
          assert2(typeof Module["wasmMemory"] == "undefined", "Use of `wasmMemory` detected.  Use -sIMPORTED_MEMORY to define wasmMemory externally");
          assert2(typeof Module["INITIAL_MEMORY"] == "undefined", "Detected runtime INITIAL_MEMORY setting.  Use -sIMPORTED_MEMORY to define wasmMemory dynamically");
        }
        var missingLibrarySymbols = [
          "writeI53ToI64",
          "writeI53ToI64Clamped",
          "writeI53ToI64Signaling",
          "writeI53ToU64Clamped",
          "writeI53ToU64Signaling",
          "readI53FromI64",
          "readI53FromU64",
          "convertI32PairToI53",
          "convertI32PairToI53Checked",
          "convertU32PairToI53",
          "getTempRet0",
          "setTempRet0",
          "zeroMemory",
          "exitJS",
          "inetPton4",
          "inetNtop4",
          "inetPton6",
          "inetNtop6",
          "readSockaddr",
          "writeSockaddr",
          "emscriptenLog",
          "runMainThreadEmAsm",
          "jstoi_q",
          "listenOnce",
          "autoResumeAudioContext",
          "getDynCaller",
          "dynCall",
          "handleException",
          "keepRuntimeAlive",
          "runtimeKeepalivePush",
          "runtimeKeepalivePop",
          "callUserCallback",
          "maybeExit",
          "asmjsMangle",
          "HandleAllocator",
          "getNativeTypeSize",
          "addOnInit",
          "addOnPostCtor",
          "addOnPreMain",
          "addOnExit",
          "STACK_SIZE",
          "STACK_ALIGN",
          "POINTER_SIZE",
          "ASSERTIONS",
          "ccall",
          "cwrap",
          "uleb128Encode",
          "sigToWasmTypes",
          "generateFuncType",
          "convertJsFunctionToWasm",
          "getEmptyTableSlot",
          "updateTableMap",
          "getFunctionAddress",
          "addFunction",
          "removeFunction",
          "reallyNegative",
          "unSign",
          "strLen",
          "reSign",
          "formatString",
          "intArrayToString",
          "AsciiToString",
          "stringToAscii",
          "stringToNewUTF8",
          "stringToUTF8OnStack",
          "writeArrayToMemory",
          "registerKeyEventCallback",
          "maybeCStringToJsString",
          "findEventTarget",
          "getBoundingClientRect",
          "fillMouseEventData",
          "registerMouseEventCallback",
          "registerWheelEventCallback",
          "registerUiEventCallback",
          "registerFocusEventCallback",
          "fillDeviceOrientationEventData",
          "registerDeviceOrientationEventCallback",
          "fillDeviceMotionEventData",
          "registerDeviceMotionEventCallback",
          "screenOrientation",
          "fillOrientationChangeEventData",
          "registerOrientationChangeEventCallback",
          "fillFullscreenChangeEventData",
          "registerFullscreenChangeEventCallback",
          "JSEvents_requestFullscreen",
          "JSEvents_resizeCanvasForFullscreen",
          "registerRestoreOldStyle",
          "hideEverythingExceptGivenElement",
          "restoreHiddenElements",
          "setLetterbox",
          "softFullscreenResizeWebGLRenderTarget",
          "doRequestFullscreen",
          "fillPointerlockChangeEventData",
          "registerPointerlockChangeEventCallback",
          "registerPointerlockErrorEventCallback",
          "requestPointerLock",
          "fillVisibilityChangeEventData",
          "registerVisibilityChangeEventCallback",
          "registerTouchEventCallback",
          "fillGamepadEventData",
          "registerGamepadEventCallback",
          "registerBeforeUnloadEventCallback",
          "fillBatteryEventData",
          "battery",
          "registerBatteryEventCallback",
          "setCanvasElementSize",
          "getCanvasElementSize",
          "jsStackTrace",
          "getCallstack",
          "convertPCtoSourceLocation",
          "checkWasiClock",
          "wasiRightsToMuslOFlags",
          "wasiOFlagsToMuslOFlags",
          "safeSetTimeout",
          "setImmediateWrapped",
          "safeRequestAnimationFrame",
          "clearImmediateWrapped",
          "registerPostMainLoop",
          "registerPreMainLoop",
          "getPromise",
          "makePromise",
          "idsToPromises",
          "makePromiseCallback",
          "Browser_asyncPrepareDataCounter",
          "isLeapYear",
          "ydayFromDate",
          "arraySum",
          "addDays",
          "getSocketFromFD",
          "getSocketAddress",
          "FS_mkdirTree",
          "_setNetworkCallback",
          "heapObjectForWebGLType",
          "toTypedArrayIndex",
          "webgl_enable_ANGLE_instanced_arrays",
          "webgl_enable_OES_vertex_array_object",
          "webgl_enable_WEBGL_draw_buffers",
          "webgl_enable_WEBGL_multi_draw",
          "webgl_enable_EXT_polygon_offset_clamp",
          "webgl_enable_EXT_clip_control",
          "webgl_enable_WEBGL_polygon_mode",
          "emscriptenWebGLGet",
          "computeUnpackAlignedImageSize",
          "colorChannelsInGlTextureFormat",
          "emscriptenWebGLGetTexPixelData",
          "emscriptenWebGLGetUniform",
          "webglGetUniformLocation",
          "webglPrepareUniformLocationsBeforeFirstUse",
          "webglGetLeftBracePos",
          "emscriptenWebGLGetVertexAttrib",
          "__glGetActiveAttribOrUniform",
          "writeGLArray",
          "registerWebGlEventCallback",
          "runAndAbortIfError",
          "ALLOC_NORMAL",
          "ALLOC_STACK",
          "allocate",
          "writeStringToMemory",
          "writeAsciiToMemory",
          "demangle",
          "stackTrace",
          "getFunctionArgsName",
          "createJsInvokerSignature",
          "createJsInvoker",
          "PureVirtualError",
          "registerInheritedInstance",
          "unregisterInheritedInstance",
          "getInheritedInstanceCount",
          "getLiveInheritedInstances",
          "enumReadValueFromPointer",
          "setDelayFunction",
          "validateThis",
          "count_emval_handles",
          "emval_get_global"
        ];
        missingLibrarySymbols.forEach(missingLibrarySymbol);
        var unexportedSymbols = [
          "run",
          "addRunDependency",
          "removeRunDependency",
          "out",
          "err",
          "callMain",
          "abort",
          "wasmMemory",
          "wasmExports",
          "HEAPF32",
          "HEAPF64",
          "HEAP8",
          "HEAPU8",
          "HEAP16",
          "HEAPU16",
          "HEAP32",
          "HEAPU32",
          "HEAP64",
          "HEAPU64",
          "writeStackCookie",
          "checkStackCookie",
          "INT53_MAX",
          "INT53_MIN",
          "bigintToI53Checked",
          "stackSave",
          "stackRestore",
          "stackAlloc",
          "ptrToString",
          "getHeapMax",
          "growMemory",
          "ENV",
          "ERRNO_CODES",
          "strError",
          "DNS",
          "Protocols",
          "Sockets",
          "timers",
          "warnOnce",
          "readEmAsmArgsArray",
          "readEmAsmArgs",
          "runEmAsmFunction",
          "getExecutableName",
          "asyncLoad",
          "alignMemory",
          "mmapAlloc",
          "wasmTable",
          "noExitRuntime",
          "addOnPreRun",
          "addOnPostRun",
          "freeTableIndexes",
          "functionsInTableMap",
          "setValue",
          "getValue",
          "PATH",
          "PATH_FS",
          "UTF8Decoder",
          "UTF8ArrayToString",
          "UTF8ToString",
          "stringToUTF8Array",
          "stringToUTF8",
          "lengthBytesUTF8",
          "intArrayFromString",
          "UTF16Decoder",
          "UTF16ToString",
          "stringToUTF16",
          "lengthBytesUTF16",
          "UTF32ToString",
          "stringToUTF32",
          "lengthBytesUTF32",
          "JSEvents",
          "specialHTMLTargets",
          "findCanvasEventTarget",
          "currentFullscreenStrategy",
          "restoreOldWindowedStyle",
          "UNWIND_CACHE",
          "ExitStatus",
          "getEnvStrings",
          "doReadv",
          "doWritev",
          "initRandomFill",
          "randomFill",
          "emSetImmediate",
          "emClearImmediate_deps",
          "emClearImmediate",
          "promiseMap",
          "getExceptionMessageCommon",
          "getCppExceptionTag",
          "getCppExceptionThrownObjectFromWebAssemblyException",
          "Browser",
          "requestFullscreen",
          "requestFullScreen",
          "setCanvasSize",
          "getUserMedia",
          "createContext",
          "getPreloadedImageData__data",
          "wget",
          "MONTH_DAYS_REGULAR",
          "MONTH_DAYS_LEAP",
          "MONTH_DAYS_REGULAR_CUMULATIVE",
          "MONTH_DAYS_LEAP_CUMULATIVE",
          "SYSCALLS",
          "preloadPlugins",
          "FS_createPreloadedFile",
          "FS_modeStringToFlags",
          "FS_getMode",
          "FS_stdin_getChar_buffer",
          "FS_stdin_getChar",
          "FS_unlink",
          "FS_createPath",
          "FS_createDevice",
          "FS_readFile",
          "FS",
          "FS_root",
          "FS_mounts",
          "FS_devices",
          "FS_streams",
          "FS_nextInode",
          "FS_nameTable",
          "FS_currentPath",
          "FS_initialized",
          "FS_ignorePermissions",
          "FS_filesystems",
          "FS_syncFSRequests",
          "FS_readFiles",
          "FS_lookupPath",
          "FS_getPath",
          "FS_hashName",
          "FS_hashAddNode",
          "FS_hashRemoveNode",
          "FS_lookupNode",
          "FS_createNode",
          "FS_destroyNode",
          "FS_isRoot",
          "FS_isMountpoint",
          "FS_isFile",
          "FS_isDir",
          "FS_isLink",
          "FS_isChrdev",
          "FS_isBlkdev",
          "FS_isFIFO",
          "FS_isSocket",
          "FS_flagsToPermissionString",
          "FS_nodePermissions",
          "FS_mayLookup",
          "FS_mayCreate",
          "FS_mayDelete",
          "FS_mayOpen",
          "FS_checkOpExists",
          "FS_nextfd",
          "FS_getStreamChecked",
          "FS_getStream",
          "FS_createStream",
          "FS_closeStream",
          "FS_dupStream",
          "FS_doSetAttr",
          "FS_chrdev_stream_ops",
          "FS_major",
          "FS_minor",
          "FS_makedev",
          "FS_registerDevice",
          "FS_getDevice",
          "FS_getMounts",
          "FS_syncfs",
          "FS_mount",
          "FS_unmount",
          "FS_lookup",
          "FS_mknod",
          "FS_statfs",
          "FS_statfsStream",
          "FS_statfsNode",
          "FS_create",
          "FS_mkdir",
          "FS_mkdev",
          "FS_symlink",
          "FS_rename",
          "FS_rmdir",
          "FS_readdir",
          "FS_readlink",
          "FS_stat",
          "FS_fstat",
          "FS_lstat",
          "FS_doChmod",
          "FS_chmod",
          "FS_lchmod",
          "FS_fchmod",
          "FS_doChown",
          "FS_chown",
          "FS_lchown",
          "FS_fchown",
          "FS_doTruncate",
          "FS_truncate",
          "FS_ftruncate",
          "FS_utime",
          "FS_open",
          "FS_close",
          "FS_isClosed",
          "FS_llseek",
          "FS_read",
          "FS_write",
          "FS_mmap",
          "FS_msync",
          "FS_ioctl",
          "FS_writeFile",
          "FS_cwd",
          "FS_chdir",
          "FS_createDefaultDirectories",
          "FS_createDefaultDevices",
          "FS_createSpecialDirectories",
          "FS_createStandardStreams",
          "FS_staticInit",
          "FS_init",
          "FS_quit",
          "FS_findObject",
          "FS_analyzePath",
          "FS_createFile",
          "FS_createDataFile",
          "FS_forceLoadFile",
          "FS_createLazyFile",
          "FS_absolutePath",
          "FS_createFolder",
          "FS_createLink",
          "FS_joinPath",
          "FS_mmapAlloc",
          "FS_standardizePath",
          "MEMFS",
          "TTY",
          "PIPEFS",
          "SOCKFS",
          "tempFixedLengthArray",
          "miniTempWebGLFloatBuffers",
          "miniTempWebGLIntBuffers",
          "GL",
          "AL",
          "GLUT",
          "EGL",
          "GLEW",
          "IDBStore",
          "SDL",
          "SDL_gfx",
          "allocateUTF8",
          "allocateUTF8OnStack",
          "print",
          "printErr",
          "jstoi_s",
          "InternalError",
          "BindingError",
          "throwInternalError",
          "throwBindingError",
          "registeredTypes",
          "awaitingDependencies",
          "typeDependencies",
          "tupleRegistrations",
          "structRegistrations",
          "sharedRegisterType",
          "whenDependentTypesAreResolved",
          "embind_charCodes",
          "embind_init_charCodes",
          "readLatin1String",
          "getTypeName",
          "getFunctionName",
          "heap32VectorToArray",
          "requireRegisteredType",
          "usesDestructorStack",
          "checkArgCount",
          "getRequiredArgCount",
          "UnboundTypeError",
          "GenericWireTypeSize",
          "EmValType",
          "EmValOptionalType",
          "throwUnboundTypeError",
          "ensureOverloadTable",
          "exposePublicSymbol",
          "replacePublicSymbol",
          "createNamedFunction",
          "embindRepr",
          "registeredInstances",
          "getBasestPointer",
          "getInheritedInstance",
          "registeredPointers",
          "registerType",
          "integerReadValueFromPointer",
          "floatReadValueFromPointer",
          "assertIntegerRange",
          "readPointer",
          "runDestructors",
          "craftInvokerFunction",
          "embind__requireFunction",
          "genericPointerToWireType",
          "constNoSmartPtrRawPointerToWireType",
          "nonConstNoSmartPtrRawPointerToWireType",
          "init_RegisteredPointer",
          "RegisteredPointer",
          "RegisteredPointer_fromWireType",
          "runDestructor",
          "releaseClassHandle",
          "finalizationRegistry",
          "detachFinalizer_deps",
          "detachFinalizer",
          "attachFinalizer",
          "makeClassHandle",
          "init_ClassHandle",
          "ClassHandle",
          "throwInstanceAlreadyDeleted",
          "deletionQueue",
          "flushPendingDeletes",
          "delayFunction",
          "RegisteredClass",
          "shallowCopyInternalPointer",
          "downcastPointer",
          "upcastPointer",
          "char_0",
          "char_9",
          "makeLegalFunctionName",
          "emval_freelist",
          "emval_handles",
          "emval_symbols",
          "getStringOrSymbol",
          "Emval",
          "emval_returnValue",
          "emval_lookupTypes",
          "emval_methodCallers",
          "emval_addMethodCaller",
          "reflectConstruct",
          "IDBFS"
        ];
        unexportedSymbols.forEach(unexportedRuntimeSymbol);
        Module["getExceptionMessage"] = getExceptionMessage;
        Module["incrementExceptionRefcount"] = incrementExceptionRefcount;
        Module["decrementExceptionRefcount"] = decrementExceptionRefcount;
        function checkIncomingModuleAPI() {
          ignoredModuleProp("fetchSettings");
        }
        var ASM_CONSTS = {
          48551: ($0, $1) => {
            let type2 = UTF8ToString($0);
            let directory = UTF8ToString($1);
            let allocatedDir = _malloc(directory.length + 1);
            stringToUTF8(directory, allocatedDir, directory.length + 1);
            let jsAllocatedDir = UTF8ToString(allocatedDir);
            if (type2 == "IDBFS") {
              FS.mkdir(jsAllocatedDir);
              FS.mount(IDBFS, {}, jsAllocatedDir);
              console.log("EmscriptenFileSystemManager: Mounting IDBFS filesystem...\n");
            } else {
              throw new Error("Unsupported filesystem type, IDBFS is supported: " + type2);
            }
            _free(allocatedDir);
          }
        };
        function syncIdb_js(populateFromFS) {
          try {
            FS.syncfs(populateFromFS, function(err2) {
              setTimeout(function() {
                if (err2) {
                  console.error("b. jsFS Error: syncing FS:", err2);
                  Module.setIdbfsSynced(false);
                } else {
                  console.log("b. jsFS synced successfully");
                  Module.setIdbfsSynced(true);
                }
              }, 1);
            });
          } catch (err2) {
            Module.setIdbfsSynced(false);
          }
        }
        var wasmImports = {
          /** @export */
          __assert_fail: ___assert_fail,
          /** @export */
          __syscall_fcntl64: ___syscall_fcntl64,
          /** @export */
          __syscall_fstat64: ___syscall_fstat64,
          /** @export */
          __syscall_ioctl: ___syscall_ioctl,
          /** @export */
          __syscall_lstat64: ___syscall_lstat64,
          /** @export */
          __syscall_newfstatat: ___syscall_newfstatat,
          /** @export */
          __syscall_openat: ___syscall_openat,
          /** @export */
          __syscall_stat64: ___syscall_stat64,
          /** @export */
          __throw_exception_with_stack_trace: ___throw_exception_with_stack_trace,
          /** @export */
          _abort_js: __abort_js,
          /** @export */
          _embind_register_bigint: __embind_register_bigint,
          /** @export */
          _embind_register_bool: __embind_register_bool,
          /** @export */
          _embind_register_class: __embind_register_class,
          /** @export */
          _embind_register_class_class_function: __embind_register_class_class_function,
          /** @export */
          _embind_register_class_constructor: __embind_register_class_constructor,
          /** @export */
          _embind_register_class_function: __embind_register_class_function,
          /** @export */
          _embind_register_emval: __embind_register_emval,
          /** @export */
          _embind_register_float: __embind_register_float,
          /** @export */
          _embind_register_function: __embind_register_function,
          /** @export */
          _embind_register_integer: __embind_register_integer,
          /** @export */
          _embind_register_memory_view: __embind_register_memory_view,
          /** @export */
          _embind_register_optional: __embind_register_optional,
          /** @export */
          _embind_register_std_string: __embind_register_std_string,
          /** @export */
          _embind_register_std_wstring: __embind_register_std_wstring,
          /** @export */
          _embind_register_void: __embind_register_void,
          /** @export */
          _emval_call_method: __emval_call_method,
          /** @export */
          _emval_decref: __emval_decref,
          /** @export */
          _emval_get_method_caller: __emval_get_method_caller,
          /** @export */
          _emval_incref: __emval_incref,
          /** @export */
          _emval_new_array: __emval_new_array,
          /** @export */
          _emval_new_cstring: __emval_new_cstring,
          /** @export */
          _emval_new_object: __emval_new_object,
          /** @export */
          _emval_run_destructors: __emval_run_destructors,
          /** @export */
          _emval_set_property: __emval_set_property,
          /** @export */
          _emval_take_value: __emval_take_value,
          /** @export */
          _tzset_js: __tzset_js,
          /** @export */
          emscripten_asm_const_int: _emscripten_asm_const_int,
          /** @export */
          emscripten_resize_heap: _emscripten_resize_heap,
          /** @export */
          environ_get: _environ_get,
          /** @export */
          environ_sizes_get: _environ_sizes_get,
          /** @export */
          fd_close: _fd_close,
          /** @export */
          fd_read: _fd_read,
          /** @export */
          fd_seek: _fd_seek,
          /** @export */
          fd_write: _fd_write,
          /** @export */
          syncIdb_js
        };
        var wasmExports = yield createWasm();
        var ___getTypeName = createExportWrapper("__getTypeName", 1);
        var _malloc = createExportWrapper("malloc", 1);
        var _free = createExportWrapper("free", 1);
        var _fflush = createExportWrapper("fflush", 1);
        var _emscripten_stack_get_end = wasmExports["emscripten_stack_get_end"];
        wasmExports["emscripten_stack_get_base"];
        var _strerror = createExportWrapper("strerror", 1);
        var ___trap = wasmExports["__trap"];
        var _emscripten_stack_init = wasmExports["emscripten_stack_init"];
        wasmExports["emscripten_stack_get_free"];
        var __emscripten_stack_restore = wasmExports["_emscripten_stack_restore"];
        var __emscripten_stack_alloc = wasmExports["_emscripten_stack_alloc"];
        var _emscripten_stack_get_current = wasmExports["emscripten_stack_get_current"];
        var ___cxa_decrement_exception_refcount = createExportWrapper("__cxa_decrement_exception_refcount", 1);
        var ___cxa_increment_exception_refcount = createExportWrapper("__cxa_increment_exception_refcount", 1);
        var ___thrown_object_from_unwind_exception = createExportWrapper("__thrown_object_from_unwind_exception", 1);
        var ___get_exception_message = createExportWrapper("__get_exception_message", 3);
        var ___cpp_exception;
        var calledRun;
        function stackCheckInit() {
          _emscripten_stack_init();
          writeStackCookie();
        }
        function run() {
          if (runDependencies > 0) {
            dependenciesFulfilled = run;
            return;
          }
          stackCheckInit();
          preRun();
          if (runDependencies > 0) {
            dependenciesFulfilled = run;
            return;
          }
          function doRun() {
            var _a3;
            assert2(!calledRun);
            calledRun = true;
            Module["calledRun"] = true;
            if (ABORT)
              return;
            initRuntime();
            readyPromiseResolve(Module);
            (_a3 = Module["onRuntimeInitialized"]) == null ? void 0 : _a3.call(Module);
            consumedModuleProp("onRuntimeInitialized");
            assert2(!Module["_main"], 'compiled without a main, but one is present. if you added it from JS, use Module["onRuntimeInitialized"]');
            postRun();
          }
          if (Module["setStatus"]) {
            Module["setStatus"]("Running...");
            setTimeout(() => {
              setTimeout(() => Module["setStatus"](""), 1);
              doRun();
            }, 1);
          } else {
            doRun();
          }
          checkStackCookie();
        }
        function preInit() {
          if (Module["preInit"]) {
            if (typeof Module["preInit"] == "function")
              Module["preInit"] = [Module["preInit"]];
            while (Module["preInit"].length > 0) {
              Module["preInit"].shift()();
            }
          }
          consumedModuleProp("preInit");
        }
        preInit();
        run();
        moduleRtn = readyPromise;
        for (const prop of Object.keys(Module)) {
          if (!(prop in moduleArg)) {
            Object.defineProperty(moduleArg, prop, {
              configurable: true,
              get() {
                abort(`Access to module property ('${prop}') is no longer possible via the module constructor argument; Instead, use the result of the module constructor.`);
              }
            });
          }
        }
        return moduleRtn;
      });
    };
  })();
  const hnswlib210c0872 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
    __proto__: null,
    default: hnswlib$1
  }, Symbol.toStringTag, { value: "Module" }));
  function handleGetModelStatus() {
    return __async(this, null, function* () {
      try {
        if (typeof chrome === "undefined" || !chrome.storage || !chrome.storage.local) {
          console.error("Background: chrome.storage.local is not available for status query");
          return {
            success: true,
            status: {
              initializationStatus: "idle",
              downloadProgress: 0,
              isDownloading: false,
              lastUpdated: Date.now()
            }
          };
        }
        const result2 = yield chrome.storage.local.get(["modelState"]);
        const modelState = result2.modelState || {
          status: "idle",
          downloadProgress: 0,
          isDownloading: false,
          lastUpdated: Date.now()
        };
        return {
          success: true,
          status: {
            initializationStatus: modelState.status,
            downloadProgress: modelState.downloadProgress,
            isDownloading: modelState.isDownloading,
            lastUpdated: modelState.lastUpdated,
            errorMessage: modelState.errorMessage,
            errorType: modelState.errorType
          }
        };
      } catch (error2) {
        console.error("Failed to get model status:", error2);
        return { success: false, error: error2.message };
      }
    });
  }
  const semanticSimilarity = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
    __proto__: null,
    handleGetModelStatus
  }, Symbol.toStringTag, { value: "Module" }));
  return result$1;
})();
